[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\ncover/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\n.pybuilder/\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n#   For a library or package, you might want to ignore these files since the code is\n#   intended to run in multiple environments; otherwise, check them in:\n# .python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# pytype static type analyzer\n.pytype/\n\n# Cython debug symbols\ncython_debug/\n\n# VS Code #\n.vscode/*\n!.vscode/tasks.json\n!.vscode/launch.json\n!.vscode/settings.json\n*.code-workspace\n\n# VS Code Patch #\n# Ignore all local history of files\n.history\n.ionide\n"
  },
  {
    "path": ".pylintrc",
    "content": "[MASTER]\n\n# A comma-separated list of package or module names from where C extensions may\n# be loaded. Extensions are loading into the active Python interpreter and may\n# run arbitrary code.\nextension-pkg-whitelist=btrfsutil\n\n# Specify a score threshold to be exceeded before program exits with error.\nfail-under=10.0\n\n# Add files or directories to the blacklist. They should be base names, not\n# paths.\nignore=CVS\n\n# Add files or directories matching the regex patterns to the blacklist. The\n# regex matches against base names, not paths.\nignore-patterns=\n\n# Python code to execute, usually for sys.path manipulation such as\n# pygtk.require().\ninit-hook='import sys, os; sys.path.append(os.path.join(os.getcwd(), \"src\", \"refind_btrfs\"))'\n\n# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the\n# number of processors available to use.\njobs=1\n\n# Control the amount of potential inferred values when inferring a single\n# object. This can help the performance when dealing with large functions or\n# complex, nested conditions.\nlimit-inference-results=100\n\n# List of plugins (as comma separated values of python module names) to load,\n# usually to register additional checkers.\nload-plugins=\n\n# Pickle collected data for later comparisons.\npersistent=yes\n\n# When enabled, pylint would attempt to guess common misconfiguration and emit\n# user-friendly hints instead of false-positive error messages.\nsuggestion-mode=yes\n\n# Allow loading of arbitrary C extensions. Extensions are imported into the\n# active Python interpreter and may run arbitrary code.\nunsafe-load-any-extension=no\n\n\n[MESSAGES CONTROL]\n\n# Only show warnings with the listed confidence levels. Leave empty to show\n# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.\nconfidence=\n\n# Disable the message, report, category or checker with the given id(s). You\n# can either give multiple identifiers separated by comma (,) or put this\n# option multiple times (only on the command line, not in the configuration\n# file where it should appear only once). You can also use \"--disable=all\" to\n# disable everything first and then reenable specific checks. For example, if\n# you want to run only the similarities checker, you can use \"--disable=all\n# --enable=similarities\". If you want to run only the classes checker, but have\n# no Warning level messages displayed, use \"--disable=all --enable=classes\n# --disable=W\".\ndisable=missing-module-docstring,\n        missing-class-docstring,\n        missing-function-docstring,\n        unsubscriptable-object,\n        inherit-non-class,\n        too-few-public-methods,\n        broad-except,\n        print-statement,\n        parameter-unpacking,\n        unpacking-in-except,\n        old-raise-syntax,\n        backtick,\n        long-suffix,\n        old-ne-operator,\n        old-octal-literal,\n        import-star-module-level,\n        non-ascii-bytes-literal,\n        raw-checker-failed,\n        bad-inline-option,\n        locally-disabled,\n        file-ignored,\n        suppressed-message,\n        useless-suppression,\n        deprecated-pragma,\n        use-symbolic-message-instead,\n        apply-builtin,\n        basestring-builtin,\n        buffer-builtin,\n        cmp-builtin,\n        coerce-builtin,\n        execfile-builtin,\n        file-builtin,\n        long-builtin,\n        raw_input-builtin,\n        reduce-builtin,\n        standarderror-builtin,\n        unicode-builtin,\n        xrange-builtin,\n        coerce-method,\n        delslice-method,\n        getslice-method,\n        setslice-method,\n        no-absolute-import,\n        old-division,\n        dict-iter-method,\n        dict-view-method,\n        next-method-called,\n        metaclass-assignment,\n        indexing-exception,\n        raising-string,\n        reload-builtin,\n        oct-method,\n        hex-method,\n        nonzero-method,\n        cmp-method,\n        input-builtin,\n        round-builtin,\n        intern-builtin,\n        unichr-builtin,\n        map-builtin-not-iterating,\n        zip-builtin-not-iterating,\n        range-builtin-not-iterating,\n        filter-builtin-not-iterating,\n        using-cmp-argument,\n        eq-without-hash,\n        div-method,\n        idiv-method,\n        rdiv-method,\n        exception-message-attribute,\n        invalid-str-codec,\n        sys-max-int,\n        bad-python3-import,\n        deprecated-string-function,\n        deprecated-str-translate-call,\n        deprecated-itertools-function,\n        deprecated-types-field,\n        next-method-defined,\n        dict-items-not-iterating,\n        dict-keys-not-iterating,\n        dict-values-not-iterating,\n        deprecated-operator-function,\n        deprecated-urllib-function,\n        xreadlines-attribute,\n        deprecated-sys-function,\n        exception-escape,\n        comprehension-escape\n\n# Enable the message, report, category or checker with the given id(s). You can\n# either give multiple identifier separated by comma (,) or put this option\n# multiple time (only on the command line, not in the configuration file where\n# it should appear only once). See also the \"--disable\" option for examples.\nenable=c-extension-no-member,\n       unused-import,\n       unused-wildcard-import\n\n\n[REPORTS]\n\n# Python expression which should return a score less than or equal to 10. You\n# have access to the variables 'error', 'warning', 'refactor', and 'convention'\n# which contain the number of messages in each category, as well as 'statement'\n# which is the total number of statements analyzed. This score is used by the\n# global evaluation report (RP0004).\nevaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)\n\n# Template used to display messages. This is a python new-style format string\n# used to format the message information. See doc for all details.\n#msg-template=\n\n# Set the output format. Available formats are text, parseable, colorized, json\n# and msvs (visual studio). You can also give a reporter class, e.g.\n# mypackage.mymodule.MyReporterClass.\noutput-format=text\n\n# Tells whether to display a full report or only the messages.\nreports=no\n\n# Activate the evaluation score.\nscore=yes\n\n\n[REFACTORING]\n\n# Maximum number of nested blocks for function / method body\nmax-nested-blocks=5\n\n# Complete name of functions that never returns. When checking for\n# inconsistent-return-statements if a never returning function is called then\n# it will be considered as an explicit return statement and no message will be\n# printed.\nnever-returning-functions=sys.exit\n\n\n[BASIC]\n\n# Naming style matching correct argument names.\nargument-naming-style=snake_case\n\n# Regular expression matching correct argument names. Overrides argument-\n# naming-style.\n#argument-rgx=\n\n# Naming style matching correct attribute names.\nattr-naming-style=snake_case\n\n# Regular expression matching correct attribute names. Overrides attr-naming-\n# style.\n#attr-rgx=\n\n# Bad variable names which should always be refused, separated by a comma.\nbad-names=foo,\n          bar,\n          baz,\n          toto,\n          tutu,\n          tata\n\n# Bad variable names regexes, separated by a comma. If names match any regex,\n# they will always be refused\nbad-names-rgxs=\n\n# Naming style matching correct class attribute names.\nclass-attribute-naming-style=any\n\n# Regular expression matching correct class attribute names. Overrides class-\n# attribute-naming-style.\n#class-attribute-rgx=\n\n# Naming style matching correct class names.\nclass-naming-style=PascalCase\n\n# Regular expression matching correct class names. Overrides class-naming-\n# style.\n#class-rgx=\n\n# Naming style matching correct constant names.\nconst-naming-style=UPPER_CASE\n\n# Regular expression matching correct constant names. Overrides const-naming-\n# style.\n#const-rgx=\n\n# Minimum line length for functions/classes that require docstrings, shorter\n# ones are exempt.\ndocstring-min-length=-1\n\n# Naming style matching correct function names.\nfunction-naming-style=snake_case\n\n# Regular expression matching correct function names. Overrides function-\n# naming-style.\n#function-rgx=\n\n# Good variable names which should always be accepted, separated by a comma.\ngood-names=e,\n           i,\n           j,\n           k,\n           ex,\n           Run,\n           _\n\n# Good variable names regexes, separated by a comma. If names match any regex,\n# they will always be accepted\ngood-names-rgxs=\n\n# Include a hint for the correct naming format with invalid-name.\ninclude-naming-hint=no\n\n# Naming style matching correct inline iteration names.\ninlinevar-naming-style=any\n\n# Regular expression matching correct inline iteration names. Overrides\n# inlinevar-naming-style.\n#inlinevar-rgx=\n\n# Naming style matching correct method names.\nmethod-naming-style=snake_case\n\n# Regular expression matching correct method names. Overrides method-naming-\n# style.\n#method-rgx=\n\n# Naming style matching correct module names.\nmodule-naming-style=snake_case\n\n# Regular expression matching correct module names. Overrides module-naming-\n# style.\n#module-rgx=\n\n# Colon-delimited sets of names that determine each other's naming style when\n# the name regexes allow several styles.\nname-group=\n\n# Regular expression which should only match function or class names that do\n# not require a docstring.\nno-docstring-rgx=^_\n\n# List of decorators that produce properties, such as abc.abstractproperty. Add\n# to this list to register other decorators that produce valid properties.\n# These decorators are taken in consideration only for invalid-name.\nproperty-classes=abc.abstractproperty\n\n# Naming style matching correct variable names.\nvariable-naming-style=snake_case\n\n# Regular expression matching correct variable names. Overrides variable-\n# naming-style.\n#variable-rgx=\n\n\n[FORMAT]\n\n# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.\nexpected-line-ending-format=\n\n# Regexp for a line that is allowed to be longer than the limit.\nignore-long-lines=^\\s*(# )?<?https?://\\S+>?$\n\n# Number of spaces of indent required inside a hanging or continued line.\nindent-after-paren=4\n\n# String used as indentation unit. This is usually \"    \" (4 spaces) or \"\\t\" (1\n# tab).\nindent-string='    '\n\n# Maximum number of characters on a single line.\nmax-line-length=100\n\n# Maximum number of lines in a module.\nmax-module-lines=1000\n\n# Allow the body of a class to be on the same line as the declaration if body\n# contains single statement.\nsingle-line-class-stmt=no\n\n# Allow the body of an if to be on the same line as the test if there is no\n# else.\nsingle-line-if-stmt=no\n\n\n[LOGGING]\n\n# The type of string formatting that logging methods do. `old` means using %\n# formatting, `new` is for `{}` formatting.\nlogging-format-style=old\n\n# Logging modules to check that the string format arguments are in logging\n# function parameter format.\nlogging-modules=logging\n\n\n[MISCELLANEOUS]\n\n# List of note tags to take in consideration, separated by a comma.\nnotes=FIXME,\n      XXX,\n      TODO\n\n# Regular expression of note tags to take in consideration.\n#notes-rgx=\n\n\n[SIMILARITIES]\n\n# Ignore comments when computing similarities.\nignore-comments=yes\n\n# Ignore docstrings when computing similarities.\nignore-docstrings=yes\n\n# Ignore imports when computing similarities.\nignore-imports=no\n\n# Minimum lines number of a similarity.\nmin-similarity-lines=4\n\n\n[SPELLING]\n\n# Limits count of emitted suggestions for spelling mistakes.\nmax-spelling-suggestions=4\n\n# Spelling dictionary name. Available dictionaries: none. To make it work,\n# install the python-enchant package.\nspelling-dict=\n\n# List of comma separated words that should not be checked.\nspelling-ignore-words=\n\n# A path to a file that contains the private dictionary; one word per line.\nspelling-private-dict-file=\n\n# Tells whether to store unknown words to the private dictionary (see the\n# --spelling-private-dict-file option) instead of raising a message.\nspelling-store-unknown-words=no\n\n\n[STRING]\n\n# This flag controls whether inconsistent-quotes generates a warning when the\n# character used as a quote delimiter is used inconsistently within a module.\ncheck-quote-consistency=no\n\n# This flag controls whether the implicit-str-concat should generate a warning\n# on implicit string concatenation in sequences defined over several lines.\ncheck-str-concat-over-line-jumps=no\n\n\n[TYPECHECK]\n\n# List of decorators that produce context managers, such as\n# contextlib.contextmanager. Add to this list to register other decorators that\n# produce valid context managers.\ncontextmanager-decorators=contextlib.contextmanager\n\n# List of members which are set dynamically and missed by pylint inference\n# system, and so shouldn't trigger E1101 when accessed. Python regular\n# expressions are accepted.\ngenerated-members=\n\n# Tells whether missing members accessed in mixin class should be ignored. A\n# mixin class is detected if its name ends with \"mixin\" (case insensitive).\nignore-mixin-members=yes\n\n# Tells whether to warn about missing members when the owner of the attribute\n# is inferred to be None.\nignore-none=yes\n\n# This flag controls whether pylint should warn about no-member and similar\n# checks whenever an opaque object is returned when inferring. The inference\n# can return multiple potential results while evaluating a Python object, but\n# some branches might not be evaluated, which results in partial inference. In\n# that case, it might be useful to still emit no-member and other checks for\n# the rest of the inferred objects.\nignore-on-opaque-inference=yes\n\n# List of class names for which member attributes should not be checked (useful\n# for classes with dynamically set attributes). This supports the use of\n# qualified names.\nignored-classes=optparse.Values,thread._local,_thread._local\n\n# List of module names for which member attributes should not be checked\n# (useful for modules/projects where namespaces are manipulated during runtime\n# and thus existing member attributes cannot be deduced by static analysis). It\n# supports qualified module names, as well as Unix pattern matching.\nignored-modules=\n\n# Show a hint with possible names when a member name was not found. The aspect\n# of finding the hint is based on edit distance.\nmissing-member-hint=yes\n\n# The minimum edit distance a name should have in order to be considered a\n# similar match for a missing member name.\nmissing-member-hint-distance=1\n\n# The total number of similar names that should be taken in consideration when\n# showing a hint for a missing member.\nmissing-member-max-choices=1\n\n# List of decorators that change the signature of a decorated function.\nsignature-mutators=\n\n\n[VARIABLES]\n\n# List of additional names supposed to be defined in builtins. Remember that\n# you should avoid defining new builtins when possible.\nadditional-builtins=\n\n# Tells whether unused global variables should be treated as a violation.\nallow-global-unused-variables=yes\n\n# List of strings which can identify a callback function by name. A callback\n# name must start or end with one of those strings.\ncallbacks=cb_,\n          _cb\n\n# A regular expression matching the name of dummy variables (i.e. expected to\n# not be used).\ndummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_\n\n# Argument names that match this expression will be ignored. Default to name\n# with leading underscore.\nignored-argument-names=_.*|^ignored_|^unused_\n\n# Tells whether we should check for unused import in __init__ files.\ninit-import=no\n\n# List of qualified module names which can have objects that can redefine\n# builtins.\nredefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io\n\n\n[CLASSES]\n\n# List of method names used to declare (i.e. assign) instance attributes.\ndefining-attr-methods=__init__,\n                      __new__,\n                      setUp,\n                      __post_init__\n\n# List of member names, which should be excluded from the protected access\n# warning.\nexclude-protected=_asdict,\n                  _fields,\n                  _replace,\n                  _source,\n                  _make\n\n# List of valid names for the first argument in a class method.\nvalid-classmethod-first-arg=cls\n\n# List of valid names for the first argument in a metaclass class method.\nvalid-metaclass-classmethod-first-arg=cls\n\n\n[DESIGN]\n\n# Maximum number of arguments for function / method.\nmax-args=5\n\n# Maximum number of attributes for a class (see R0902).\nmax-attributes=7\n\n# Maximum number of boolean expressions in an if statement (see R0916).\nmax-bool-expr=5\n\n# Maximum number of branch for function / method body.\nmax-branches=12\n\n# Maximum number of locals for function / method body.\nmax-locals=15\n\n# Maximum number of parents for a class (see R0901).\nmax-parents=7\n\n# Maximum number of public methods for a class (see R0904).\nmax-public-methods=20\n\n# Maximum number of return / yield for function / method body.\nmax-returns=6\n\n# Maximum number of statements in function / method body.\nmax-statements=50\n\n# Minimum number of public methods for a class (see R0903).\nmin-public-methods=2\n\n\n[IMPORTS]\n\n# List of modules that can be imported at any level, not just the top level\n# one.\nallow-any-import-level=\n\n# Allow wildcard imports from modules that define __all__.\nallow-wildcard-with-all=no\n\n# Analyse import fallback blocks. This can be used to support both Python 2 and\n# 3 compatible code, which means that the block might have code that exists\n# only in one or another interpreter, leading to false positives when analysed.\nanalyse-fallback-blocks=no\n\n# Deprecated modules which should not be used, separated by a comma.\ndeprecated-modules=optparse,tkinter.tix\n\n# Create a graph of external dependencies in the given file (report RP0402 must\n# not be disabled).\next-import-graph=\n\n# Create a graph of every (i.e. internal and external) dependencies in the\n# given file (report RP0402 must not be disabled).\nimport-graph=\n\n# Create a graph of internal dependencies in the given file (report RP0402 must\n# not be disabled).\nint-import-graph=\n\n# Force import order to recognize a module as part of the standard\n# compatibility libraries.\nknown-standard-library=\n\n# Force import order to recognize a module as part of a third party library.\nknown-third-party=enchant\n\n# Couples of modules and preferred modules, separated by a comma.\npreferred-modules=\n\n\n[EXCEPTIONS]\n\n# Exceptions that will emit a warning when being caught. Defaults to\n# \"BaseException, Exception\".\novergeneral-exceptions=BaseException,\n                       Exception\n"
  },
  {
    "path": ".vscode/launch.json",
    "content": "{\n    \"version\": \"0.2.0\",\n    \"configurations\": [\n        {\n            \"name\": \"Python: Module\",\n            \"type\": \"debugpy\",\n            \"request\": \"launch\",\n            \"console\": \"integratedTerminal\",\n            \"module\": \"refind_btrfs\",\n            \"cwd\": \"${workspaceFolder}/src\",\n            \"envFile\": \"${workspaceFolder}/.env\",\n            \"args\": [\n                \"--run-mode\",\n                \"one-time\"\n            ],\n            \"sudo\": true,\n            \"justMyCode\": false\n        }\n    ]\n}"
  },
  {
    "path": ".vscode/settings.json",
    "content": "{\n    \"antlr4.generation\": {\n        \"alternativeJar\": \"C:\\\\Users\\\\Luka\\\\Projects\\\\Python\\\\antlr-4.13.1-complete.jar\",\n        \"language\": \"Python3\",\n        \"listeners\": false,\n        \"mode\": \"external\",\n        \"visitors\": true\n    },\n    \"cSpell.words\": [\n        \"antlr\",\n        \"bootable\",\n        \"Bootnum\",\n        \"Btrfs\",\n        \"btrfsutil\",\n        \"bytecode\",\n        \"ELILO\",\n        \"EPERM\",\n        \"errno\",\n        \"findmnt\",\n        \"fstype\",\n        \"getpid\",\n        \"getuid\",\n        \"groupby\",\n        \"ICNS\",\n        \"IMODE\",\n        \"INITRD\",\n        \"inplace\",\n        \"ismethod\",\n        \"itertools\",\n        \"journalctl\",\n        \"levelno\",\n        \"Lsblk\",\n        \"menuentry\",\n        \"mtab\",\n        \"nargs\",\n        \"nodeps\",\n        \"nofsroot\",\n        \"ostype\",\n        \"otime\",\n        \"partuuid\",\n        \"pidfile\",\n        \"pidname\",\n        \"PTABLE\",\n        \"pttype\",\n        \"ptuuid\",\n        \"pycache\",\n        \"pylint\",\n        \"pyproject\",\n        \"PYTHONPATH\",\n        \"refind\",\n        \"rootflags\",\n        \"setuptools\",\n        \"SPDX\",\n        \"submenuentry\",\n        \"Subobject\",\n        \"suboption\",\n        \"subvol\",\n        \"subvolid\",\n        \"subvolume\",\n        \"tomlkit\",\n        \"vfat\"\n    ],\n    \"code-runner.clearPreviousOutput\": true,\n    \"code-runner.runInTerminal\": true,\n    \"python.analysis.completeFunctionParens\": true,\n    \"python.analysis.diagnosticMode\": \"workspace\",\n    \"python.analysis.extraPaths\": [\n        \"src/refind_btrfs\"\n    ],\n    \"python.defaultInterpreterPath\": \"${workspaceFolder}/.venv/bin/python\",\n    \"python.envFile\": \"${workspaceFolder}/.env\",\n    \"python.formatting.provider\": \"black\",\n    \"python.languageServer\": \"Pylance\",\n    \"python.linting.enabled\": true,\n    \"python.linting.mypyEnabled\": true,\n    \"python.linting.mypyPath\": \"${workspaceFolder}/.venv/bin/mypy\",\n    \"python.linting.pylintEnabled\": true,\n    \"python.linting.pylintPath\": \"${workspaceFolder}/.venv/bin/pylint\",\n    \"search.exclude\": {\n        \"**/.venv\": true\n    },\n    \"terminal.integrated.env.linux\": {\n        \"PYTHONPATH\": \"${env:PYTHONPATH}:${workspaceFolder}/src\"\n    }\n}"
  },
  {
    "path": "LICENSE.txt",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "MANIFEST.in",
    "content": "include pyproject.toml\ninclude *.md\ninclude LICENSE.txt\n\n# Include ANTLR generated files\nrecursive-include src/refind_btrfs/boot/antlr4 *.py\n\n# Include data files\nrecursive-include src/refind_btrfs/data *\n\n# Exclude all bytecode\nglobal-exclude *.py[cdo]\n"
  },
  {
    "path": "README.md",
    "content": "# refind-btrfs\n\n### Table of Contents\n  - [Description](#description)\n  - [Prerequisites](#prerequisites)\n  - [Installation](#installation)\n  - [Configuration](#configuration)\n  - [Example](#example)\n  - [Implementation](#implementation)\n  - [Further Efforts](#further-efforts)\n\n## Description\nThis 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).\n\nWhat it does is the following:\n* Gathers information about block devices present in the system\n* Identifies the [ESP](https://en.wikipedia.org/wiki/EFI_system_partition) (either by GPT GUID or MBR ID)\n* Gathers information about mounted filesystems (from [mtab](https://en.wikipedia.org/wiki/Mtab)) which are present on all of the found block devices\n* Identifies the root mount point and gathers information about the subvolume which is mounted at said mount point\n* Searches for snapshots of the identified subvolume in the configured directory (or directories)\n* 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)\n* 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):\n  * sets their read-only flag to false, thus making them writable\n  * creates new writable snapshots from them in the configured location\n* Aligns the root mount point in the [fstab](https://en.wikipedia.org/wiki/Fstab) file of each selected snapshot with the snapshot itself\n* Deletes outdated previously created writable snapshots (if any exist)\n* Generates new manual boot stanzas from identified ones where every relevant field is aligned with each selected snapshot\n* 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\n\nIn 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.  \nIt 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.\n\nThis 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.\n\n## Prerequisites\nThe following conditions (some are probably superfluous at this point) must be satisfied in order for this tool to function correctly:\n* mounted ESP (no automatic discovery and/or mounting is supported)\n* Btrfs formatted filesystem with a subvolume mounted as /\n* at least one snapshot of the root subvolume\n* rEFInd installation present on the ESP\n* 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:\n  * 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\n  * 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\n\n## Installation\nThis 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.\n\nIt 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).  \nBefore 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.\n\nIf you wish to check the current status and log output of the running service you can do so by executing:\n```\nsystemctl status refind-btrfs\njournalctl -u refind-btrfs -b\n```\n\nAlternatively, 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.  \nAlso, 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:\n* refind-btrfs script to /usr/bin (or wherever it is you keep your system-wide executables)\n* refind-btrfs.conf-sample as refind-btrfs.conf (without the \"-sample\" suffix) to /etc\n* refind-btrfs.service to /usr/lib/systemd/system (if you are using systemd and wish to utilize the snapshot directory watching feature)\n\nIn 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:\n```\npip install refind-btrfs[custom_icon]\n```\n\nYou 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.\n\n## Configuration\nThe 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).  \nIn 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.\n\nThe 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.  \n[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.\n\nIf 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.\n\nCustom 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.  \nIn 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/).\n\nIt 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.\n\n## Example\nGiven a setup such as this one:\n* device /dev/nvme0n1 where:\n  * the ESP is on /dev/nvme0n1p3 mounted at /efi\n  * / is on /dev/nvme0n1p8\n  * /boot is included in /dev/nvme0n1p8 (**not** a separate partition)\n* the subvolume mounted as / is named @\n* fstab file's root mount point:\n```\nUUID=95250e8a-5870-45df-a7b3-3b3ee8873c16 / btrfs rw,noatime,compress-force=zstd:2,ssd,space_cache=v2,commit=15,subvolid=256,subvol=/@ 0 0\n```\n* manual boot stanza defined in the refind.conf file (rEFInd's main config file, in this case):  \n```\nmenuentry \"Arch Linux - Stable\" {\n    icon /EFI/refind/icons/os_arch.png\n    volume ARCH\n    loader /@/boot/vmlinuz-linux\n    initrd /@/boot/initramfs-linux.img\n    options \"root=PARTUUID=048d6fcd-c88c-504d-bd51-dfc0a5bf762d rw add_efi_memmap rootflags=subvol=@ initrd=@\\boot\\intel-ucode.img\"\n    submenuentry \"Boot - fallback\" {\n        initrd /@/boot/initramfs-linux-fallback.img\n    }\n    submenuentry \"Boot - terminal\" {\n        add_options \"systemd.unit=multi-user.target\"\n    }\n}\n```\n* 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):\n\n    | Absolute Path          | Time of Creation    | Subvolume ID |\n    | ---------------------- | ------------------- | ------------ |\n    | /.snapshots/1/snapshot | 10-12-2020 01:00:00 | 498          |\n    | /.snapshots/2/snapshot | 11-12-2020 02:00:00 | 499          |\n    | /.snapshots/3/snapshot | 12-12-2020 03:00:00 | 500          |\n    | /.snapshots/4/snapshot | 13-12-2020 04:00:00 | 501          |\n    | /.snapshots/5/snapshot | 14-12-2020 05:00:00 | 502          |\n\n* refind-btrfs.conf file changed such that the \"selection_count\" option is set to 3 instead of the default 5\n\nWhen 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.\n\nAfterwards, the resultant snapshots' generated names should look like this:\n* rwsnap_2020-12-12_03-00-00_ID500,\n* rwsnap_2020-12-13_04-00-00_ID501 and\n* rwsnap_2020-12-14_05-00-00_ID502\n\nThis 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).  \n\nThe most recent snapshot's fstab file should (after being modified) contain a root mount point which looks like this:  \n\n```\nUUID=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\n```\nI'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).\n\nWith 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.  \nI'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.\n\nA 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.\n\nYou 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.\n\nThe generated file's contents (representing the generated stanza) should look like this:\n```\nmenuentry \"Arch Linux - Stable (rwsnap_2020-12-14_05-00-00_ID502)\" {\n    icon /EFI/refind/icons/os_arch.png\n    volume ARCH\n    loader /@/root/.refind-btrfs/rwsnap_2020-12-14_05-00-00_ID502/boot/vmlinuz-linux\n    initrd /@/root/.refind-btrfs/rwsnap_2020-12-14_05-00-00_ID502/boot/initramfs-linux.img\n    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\"\n    submenuentry \"Arch Linux - Stable (rwsnap_2020-12-13_04-00-00_ID501)\" {\n        loader /@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501/boot/vmlinuz-linux\n        initrd /@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501/boot/initramfs-linux.img\n        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\"\n    }\n    submenuentry \"Arch Linux - Stable (rwsnap_2020-12-12_03-00-00_ID500)\" {\n        loader /@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500/boot/vmlinuz-linux\n        initrd /@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500/boot/initramfs-linux.img\n        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\"\n    }\n}\n```\nAs 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.\n\nIf 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:\n```\nmenuentry \"Arch Linux - Stable (rwsnap_2020-12-14_05-00-00_ID502)\" {\n    icon /EFI/refind/icons/os_arch.png\n    volume ARCH\n    loader /@/root/.refind-btrfs/rwsnap_2020-12-14_05-00-00_ID502/boot/vmlinuz-linux\n    initrd /@/root/.refind-btrfs/rwsnap_2020-12-14_05-00-00_ID502/boot/initramfs-linux.img\n    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\"\n    submenuentry \"Boot - fallback (rwsnap_2020-12-14_05-00-00_ID502)\" {\n        initrd /@/root/.refind-btrfs/rwsnap_2020-12-14_05-00-00_ID502/boot/initramfs-linux-fallback.img\n    }\n    submenuentry \"Boot - terminal (rwsnap_2020-12-14_05-00-00_ID502)\" {\n        add_options \"systemd.unit=multi-user.target\"\n    }\n    submenuentry \"Arch Linux - Stable (rwsnap_2020-12-13_04-00-00_ID501)\" {\n        loader /@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501/boot/vmlinuz-linux\n        initrd /@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501/boot/initramfs-linux.img\n        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\"\n    }\n    submenuentry \"Boot - fallback (rwsnap_2020-12-13_04-00-00_ID501)\" {\n        loader /@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501/boot/vmlinuz-linux\n        initrd /@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501/boot/initramfs-linux-fallback.img\n        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\"\n    }\n    submenuentry \"Boot - terminal (rwsnap_2020-12-13_04-00-00_ID501)\" {\n        loader /@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501/boot/vmlinuz-linux\n        initrd /@/root/.refind-btrfs/rwsnap_2020-12-13_04-00-00_ID501/boot/initramfs-linux.img\n        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\"\n    }\n    submenuentry \"Arch Linux - Stable (rwsnap_2020-12-12_03-00-00_ID500)\" {\n        loader /@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500/boot/vmlinuz-linux\n        initrd /@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500/boot/initramfs-linux.img\n        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\"\n    }\n    submenuentry \"Boot - fallback (rwsnap_2020-12-12_03-00-00_ID500)\" {\n        loader /@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500/boot/vmlinuz-linux\n        initrd /@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500/boot/initramfs-linux-fallback.img\n        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\"\n    }\n    submenuentry \"Boot - terminal (rwsnap_2020-12-12_03-00-00_ID500)\" {\n        loader /@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500/boot/vmlinuz-linux\n        initrd /@/root/.refind-btrfs/rwsnap_2020-12-12_03-00-00_ID500/boot/initramfs-linux.img\n        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\"\n    }\n}\n```\n\nA 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.\n\nThis 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:\n\n![rEFInd Screenshot Default](src/refind_btrfs/data/images/refind_screenshot_default.png)\n\nHere, 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.\n\nBy 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:\n\n![rEFInd Screenshot Nord](src/refind_btrfs/data/images/refind_screenshot_nord.png)\n\n## Implementation\nMost relevant dependencies:\n* block device and ESP information is gathered using [lsblk](https://man7.org/linux/man-pages/man8/lsblk.8.html) (supports JSON output)\n* mtab information is gathered using [findmnt](https://man7.org/linux/man-pages/man8/findmnt.8.html) (same remark applies regarding the output)\n* all of the mentioned subvolume and snapshot operations are performed using [libbtrfsutil](https://github.com/kdave/btrfs-progs/tree/master/libbtrfsutil)\n* [ANLTR4](https://github.com/antlr/antlr4) was used to generate the lexer and parser required for rEFInd config files' analyses\n* [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)\n* [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\n\n[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.\n\nThe 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.\n\n## Further Efforts\nCurrently, 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.  \nThis 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.  \nWith that said, being somehow able to preview changes proposed by this tool would also be beneficial, especially after altering its configuration.\n\nA 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.\n\nGenerated 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.\n\nBut, 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.\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[build-system]\nrequires = [\"setuptools\", \"wheel\"]\nbuild-backend = \"setuptools.build_meta\"\n"
  },
  {
    "path": "setup.cfg",
    "content": "[metadata]\nname = refind_btrfs\nversion = 0.6.5\ndescription = Generate rEFInd manual boot stanzas from Btrfs snapshots\nlong_description = file: README.md\nkeywords = rEFInd, btrfs\nurl = https://github.com/Venom1991/refind-btrfs\nauthor = Luka Žaja\nauthor_email = luka.zaja@protonmail.com\nmaintainer = Luka Žaja\nmaintainer_email = luka.zaja@protonmail.com\nlicense = GNU General Public License v3 or later (GPLv3+)\nlicense_file = LICENSE.txt\nplatforms = Linux\nclassifiers = \n        Development Status :: 4 - Beta\n        Intended Audience :: End Users/Desktop\n        License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)\n        Natural Language :: English\n        Operating System :: POSIX :: Linux\n        Programming Language :: Python :: 3.11\n        Topic :: System :: Boot\n\n[options]\npackage_dir =\n    =src\npackages = find:\ninclude_package_data = True\ninstall_requires =\n    antlr4-python3-runtime\n    injector\n    more-itertools\n    pid\n    semantic-version\n    systemd-python\n    tomlkit\n    transitions\n    typeguard\n    watchdog\npython_requires = >= 3.11\n\n[options.extras_require]\ncustom_icon = Pillow\n\n[options.entry_points]\nconsole_scripts =\n    refind-btrfs = refind_btrfs:main\n\n[options.packages.find]\nwhere = src\n\n[bdist_wheel]\nuniversal = False\n"
  },
  {
    "path": "setup.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport setuptools\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as readme:\n    long_description = readme.read()\n\nsetuptools.setup(\n    name=\"refind-btrfs\",\n    version=\"0.6.5\",\n    author=\"Luka Žaja\",\n    author_email=\"luka.zaja@protonmail.com\",\n    description=\"Generate rEFInd manual boot stanzas from Btrfs snapshots\",\n    long_description=long_description,\n    long_description_content_type=\"text/markdown\",\n    keywords=\"rEFInd, btrfs\",\n    url=\"https://github.com/Venom1991/refind-btrfs\",\n    classifiers=[\n        \"Development Status :: 4 - Beta\",\n        \"Intended Audience :: End Users/Desktop\",\n        \"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)\",\n        \"Natural Language :: English\",\n        \"Operating System :: POSIX :: Linux\",\n        \"Programming Language :: Python :: 3.11\",\n        \"Topic :: System :: Boot\",\n    ],\n    package_dir={\"\": \"src\"},\n    packages=setuptools.find_packages(where=\"src\"),\n    include_package_data=True,\n    install_requires=[\n        \"antlr4-python3-runtime\",\n        \"injector\",\n        \"more-itertools\",\n        \"pid\",\n        \"semantic-version\",\n        \"systemd-python\",\n        \"tomlkit\",\n        \"transitions\",\n        \"typeguard\",\n        \"watchdog\",\n    ],\n    entry_points={\n        \"console_scripts\": [\n            \"refind-btrfs=refind_btrfs:main\",\n        ],\n    },\n    extras_require={\"custom_icon\": [\"Pillow\"]},\n    python_requires=\">=3.11\",\n)\n"
  },
  {
    "path": "src/refind_btrfs/__init__.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport os\nfrom argparse import ArgumentParser\nfrom typing import Optional\n\nfrom injector import Injector\n\nfrom refind_btrfs.common import constants\nfrom refind_btrfs.common.abc import BaseRunner\nfrom refind_btrfs.common.abc.factories import BaseLoggerFactory\nfrom refind_btrfs.common.enums import RunMode\nfrom refind_btrfs.common.exceptions import PackageConfigError\nfrom refind_btrfs.utility.helpers import check_access_rights, checked_cast, none_throws\nfrom refind_btrfs.utility.injector_modules import CLIModule, WatchdogModule\n\n\ndef initialize_injector() -> Optional[Injector]:\n    one_time_mode = RunMode.ONE_TIME.value\n    background_mode = RunMode.BACKGROUND.value\n    parser = ArgumentParser(\n        prog=\"refind-btrfs\",\n        usage=\"%(prog)s [options]\",\n        description=\"Generate rEFInd manual boot stanzas from Btrfs snapshots\",\n    )\n\n    parser.add_argument(\n        \"-rm\",\n        \"--run-mode\",\n        help=\"Mode of execution\",\n        choices=[one_time_mode, background_mode],\n        type=str,\n        nargs=\"?\",\n        const=one_time_mode,\n        default=one_time_mode,\n    )\n\n    arguments = parser.parse_args()\n    run_mode = checked_cast(str, none_throws(arguments.run_mode))\n\n    if run_mode == one_time_mode:\n        return Injector(CLIModule)\n    elif run_mode == background_mode:\n        return Injector(WatchdogModule)\n\n    return None\n\n\ndef main() -> int:\n    exit_code = os.EX_OK\n    injector = none_throws(initialize_injector())\n    logger_factory = injector.get(BaseLoggerFactory)\n    logger = logger_factory.logger(__name__)\n\n    try:\n        check_access_rights()\n\n        runner = injector.get(BaseRunner)\n        exit_code = runner.run()\n    except PackageConfigError as e:\n        exit_code = constants.EX_NOT_OK\n        logger.error(e.formatted_message)\n    except PermissionError as e:\n        exit_code = e.errno\n        logger.error(e.strerror)\n    except Exception:\n        exit_code = constants.EX_NOT_OK\n        logger.exception(constants.MESSAGE_UNEXPECTED_ERROR)\n\n    return exit_code\n"
  },
  {
    "path": "src/refind_btrfs/__main__.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport sys\n\nfrom . import main\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n"
  },
  {
    "path": "src/refind_btrfs/boot/__init__.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom .boot_options import BootOptions\nfrom .boot_stanza import BootStanza\nfrom .refind_config import RefindConfig\nfrom .sub_menu import SubMenu\n"
  },
  {
    "path": "src/refind_btrfs/boot/antlr4/RefindConfigLexer.g4",
    "content": "/*\nSPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n\nSPDX-License-Identifier: GPL-3.0-or-later\n\nrefind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\nlexer grammar RefindConfigLexer;\n\nWHITESPACE : [ \\t]+ -> skip ;\nNEWLINE : '\\r'?'\\n' ->  skip ;\nEMPTY : WHITESPACE? NEWLINE -> skip ;\nCOMMENT : '#' (~[\\n])* NEWLINE? -> skip ;\nIGNORED_OPTION\n    : (\n          'also_scan_dirs'\n        | 'also_scan_tools'\n        | 'banner'\n        | 'banner_scale'\n        | 'big_icon_size'\n        | 'csr_values'\n        | 'default_selection'\n        | 'don\\'t_scan_dirs'\n        | 'don\\'t_scan_files'\n        | 'don\\'t_scan_firmware'\n        | 'don\\'t_scan_tools'\n        | 'don\\'t_scan_volumes'\n        | 'dont_scan_dirs'\n        | 'dont_scan_files'\n        | 'dont_scan_firmware'\n        | 'dont_scan_tools'\n        | 'dont_scan_volumes'\n        | 'enable_and_lock_vmx'\n        | 'enable_mouse'\n        | 'enable_touch'\n        | 'extra_kernel_version_strings'\n        | 'fold_linux_kernels'\n        | 'follow_symlinks'\n        | 'font'\n        | 'hideui'\n        | 'icons_dir'\n        | 'linux_prefixes'\n        | 'log_level'\n        | 'max_tags'\n        | 'mouse_size'\n        | 'mouse_speed'\n        | 'resolution'\n        | 'scan_all_linux_kernels'\n        | 'scan_delay'\n        | 'scan_driver_dirs'\n        | 'scanfor'\n        | 'screensaver'\n        | 'selection_big'\n        | 'selection_small'\n        | 'showtools'\n        | 'shutdown_after_timeout'\n        | 'small_icon_size'\n        | 'spoof_osx_version'\n        | 'support_gzipped_loaders'\n        | 'textmode'\n        | 'textonly'\n        | 'timeout'\n        | 'uefi_deep_legacy_scan'\n        | 'use_graphics_for'\n        | 'use_nvram'\n        | 'windows_recovery_files'\n        | 'write_systemd_vars'\n      ) (~[\\n])* NEWLINE? -> skip ;\n\nMENU_ENTRY : (MAIN_MENU_ENTRY | SUB_MENU_ENTRY) ;\nfragment MAIN_MENU_ENTRY : 'menuentry' ;\nfragment SUB_MENU_ENTRY : 'submenuentry' ;\n\nVOLUME : 'volume' ;\nLOADER : 'loader' ;\nINITRD : 'initrd' ;\nICON : 'icon' ;\nOS_TYPE : 'ostype' WHITESPACE -> pushMode(STRICT_PARAMETER_MODE) ;\nGRAPHICS : 'graphics' WHITESPACE -> pushMode(STRICT_PARAMETER_MODE) ;\nBOOT_OPTIONS : 'options' ;\nADD_BOOT_OPTIONS : 'add_options' ;\nFIRMWARE_BOOTNUM : 'firmware_bootnum' ;\nDISABLED : 'disabled' ;\n\nINCLUDE : 'include' ;\n\nOPEN_BRACE : '{' ;\nCLOSE_BRACE : '}' ;\n\nHEX_INTEGER : HEX_DIGIT+ ;\nfragment HEX_DIGIT: [0-9a-fA-F] ;\n\nSTRING: (SINGLE_QUOTED_STRING | DOUBLE_QUOTED_STRING | UNQUOTED_STRING) ;\nfragment SINGLE_QUOTED_STRING : '\\'' (~[\\n])+ '\\'' ;\nfragment DOUBLE_QUOTED_STRING : '\"' (~[\\n])+ '\"' ;\nfragment UNQUOTED_STRING : (~[ \\t\\n])+ ;\n\nmode STRICT_PARAMETER_MODE;\n\nOS_TYPE_PARAMETER : ('MacOS' | 'Linux' | 'ELILO' | 'Windows' | 'XOM') -> popMode ;\nGRAPHICS_PARAMETER : ('on' | 'off') -> popMode ;\n"
  },
  {
    "path": "src/refind_btrfs/boot/antlr4/RefindConfigLexer.interp",
    "content": "token literal names:\nnull\nnull\nnull\nnull\nnull\nnull\nnull\n'volume'\n'loader'\n'initrd'\n'icon'\nnull\nnull\n'options'\n'add_options'\n'firmware_bootnum'\n'disabled'\n'include'\n'{'\n'}'\nnull\nnull\nnull\nnull\n\ntoken symbolic names:\nnull\nWHITESPACE\nNEWLINE\nEMPTY\nCOMMENT\nIGNORED_OPTION\nMENU_ENTRY\nVOLUME\nLOADER\nINITRD\nICON\nOS_TYPE\nGRAPHICS\nBOOT_OPTIONS\nADD_BOOT_OPTIONS\nFIRMWARE_BOOTNUM\nDISABLED\nINCLUDE\nOPEN_BRACE\nCLOSE_BRACE\nHEX_INTEGER\nSTRING\nOS_TYPE_PARAMETER\nGRAPHICS_PARAMETER\n\nrule names:\nWHITESPACE\nNEWLINE\nEMPTY\nCOMMENT\nIGNORED_OPTION\nMENU_ENTRY\nMAIN_MENU_ENTRY\nSUB_MENU_ENTRY\nVOLUME\nLOADER\nINITRD\nICON\nOS_TYPE\nGRAPHICS\nBOOT_OPTIONS\nADD_BOOT_OPTIONS\nFIRMWARE_BOOTNUM\nDISABLED\nINCLUDE\nOPEN_BRACE\nCLOSE_BRACE\nHEX_INTEGER\nHEX_DIGIT\nSTRING\nSINGLE_QUOTED_STRING\nDOUBLE_QUOTED_STRING\nUNQUOTED_STRING\nOS_TYPE_PARAMETER\nGRAPHICS_PARAMETER\n\nchannel names:\nDEFAULT_TOKEN_CHANNEL\nHIDDEN\n\nmode names:\nDEFAULT_MODE\nSTRICT_PARAMETER_MODE\n\natn:\n[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]"
  },
  {
    "path": "src/refind_btrfs/boot/antlr4/RefindConfigLexer.py",
    "content": "# Generated from c:/Users/Luka/Projects/Python/refind-btrfs/src/refind_btrfs/boot/antlr4/RefindConfigLexer.g4 by ANTLR 4.13.1\nfrom antlr4 import *\nfrom io import StringIO\nimport sys\nif sys.version_info[1] > 5:\n    from typing import TextIO\nelse:\n    from typing.io import TextIO\n\n\ndef serializedATN():\n    return [\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        20,1,20,1,21,4,21,967,8,21,11,21,12,21,968,1,22,1,22,1,23,1,23,1,\n        23,3,23,976,8,23,1,24,1,24,4,24,980,8,24,11,24,12,24,981,1,24,1,\n        24,1,25,1,25,4,25,988,8,25,11,25,12,25,989,1,25,1,25,1,26,4,26,995,\n        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,\n        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,\n        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,\n        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,\n        0,18,7,20,8,22,9,24,10,26,11,28,12,30,13,32,14,34,15,36,16,38,17,\n        40,18,42,19,44,20,46,0,48,21,50,0,52,0,54,0,56,22,58,23,2,0,1,4,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        5,115,0,0,96,97,5,111,0,0,97,98,5,95,0,0,98,99,5,115,0,0,99,100,\n        5,99,0,0,100,101,5,97,0,0,101,102,5,110,0,0,102,103,5,95,0,0,103,\n        104,5,100,0,0,104,105,5,105,0,0,105,106,5,114,0,0,106,818,5,115,\n        0,0,107,108,5,97,0,0,108,109,5,108,0,0,109,110,5,115,0,0,110,111,\n        5,111,0,0,111,112,5,95,0,0,112,113,5,115,0,0,113,114,5,99,0,0,114,\n        115,5,97,0,0,115,116,5,110,0,0,116,117,5,95,0,0,117,118,5,116,0,\n        0,118,119,5,111,0,0,119,120,5,111,0,0,120,121,5,108,0,0,121,818,\n        5,115,0,0,122,123,5,98,0,0,123,124,5,97,0,0,124,125,5,110,0,0,125,\n        126,5,110,0,0,126,127,5,101,0,0,127,818,5,114,0,0,128,129,5,98,0,\n        0,129,130,5,97,0,0,130,131,5,110,0,0,131,132,5,110,0,0,132,133,5,\n        101,0,0,133,134,5,114,0,0,134,135,5,95,0,0,135,136,5,115,0,0,136,\n        137,5,99,0,0,137,138,5,97,0,0,138,139,5,108,0,0,139,818,5,101,0,\n        0,140,141,5,98,0,0,141,142,5,105,0,0,142,143,5,103,0,0,143,144,5,\n        95,0,0,144,145,5,105,0,0,145,146,5,99,0,0,146,147,5,111,0,0,147,\n        148,5,110,0,0,148,149,5,95,0,0,149,150,5,115,0,0,150,151,5,105,0,\n        0,151,152,5,122,0,0,152,818,5,101,0,0,153,154,5,99,0,0,154,155,5,\n        115,0,0,155,156,5,114,0,0,156,157,5,95,0,0,157,158,5,118,0,0,158,\n        159,5,97,0,0,159,160,5,108,0,0,160,161,5,117,0,0,161,162,5,101,0,\n        0,162,818,5,115,0,0,163,164,5,100,0,0,164,165,5,101,0,0,165,166,\n        5,102,0,0,166,167,5,97,0,0,167,168,5,117,0,0,168,169,5,108,0,0,169,\n        170,5,116,0,0,170,171,5,95,0,0,171,172,5,115,0,0,172,173,5,101,0,\n        0,173,174,5,108,0,0,174,175,5,101,0,0,175,176,5,99,0,0,176,177,5,\n        116,0,0,177,178,5,105,0,0,178,179,5,111,0,0,179,818,5,110,0,0,180,\n        181,5,100,0,0,181,182,5,111,0,0,182,183,5,110,0,0,183,184,5,39,0,\n        0,184,185,5,116,0,0,185,186,5,95,0,0,186,187,5,115,0,0,187,188,5,\n        99,0,0,188,189,5,97,0,0,189,190,5,110,0,0,190,191,5,95,0,0,191,192,\n        5,100,0,0,192,193,5,105,0,0,193,194,5,114,0,0,194,818,5,115,0,0,\n        195,196,5,100,0,0,196,197,5,111,0,0,197,198,5,110,0,0,198,199,5,\n        39,0,0,199,200,5,116,0,0,200,201,5,95,0,0,201,202,5,115,0,0,202,\n        203,5,99,0,0,203,204,5,97,0,0,204,205,5,110,0,0,205,206,5,95,0,0,\n        206,207,5,102,0,0,207,208,5,105,0,0,208,209,5,108,0,0,209,210,5,\n        101,0,0,210,818,5,115,0,0,211,212,5,100,0,0,212,213,5,111,0,0,213,\n        214,5,110,0,0,214,215,5,39,0,0,215,216,5,116,0,0,216,217,5,95,0,\n        0,217,218,5,115,0,0,218,219,5,99,0,0,219,220,5,97,0,0,220,221,5,\n        110,0,0,221,222,5,95,0,0,222,223,5,102,0,0,223,224,5,105,0,0,224,\n        225,5,114,0,0,225,226,5,109,0,0,226,227,5,119,0,0,227,228,5,97,0,\n        0,228,229,5,114,0,0,229,818,5,101,0,0,230,231,5,100,0,0,231,232,\n        5,111,0,0,232,233,5,110,0,0,233,234,5,39,0,0,234,235,5,116,0,0,235,\n        236,5,95,0,0,236,237,5,115,0,0,237,238,5,99,0,0,238,239,5,97,0,0,\n        239,240,5,110,0,0,240,241,5,95,0,0,241,242,5,116,0,0,242,243,5,111,\n        0,0,243,244,5,111,0,0,244,245,5,108,0,0,245,818,5,115,0,0,246,247,\n        5,100,0,0,247,248,5,111,0,0,248,249,5,110,0,0,249,250,5,39,0,0,250,\n        251,5,116,0,0,251,252,5,95,0,0,252,253,5,115,0,0,253,254,5,99,0,\n        0,254,255,5,97,0,0,255,256,5,110,0,0,256,257,5,95,0,0,257,258,5,\n        118,0,0,258,259,5,111,0,0,259,260,5,108,0,0,260,261,5,117,0,0,261,\n        262,5,109,0,0,262,263,5,101,0,0,263,818,5,115,0,0,264,265,5,100,\n        0,0,265,266,5,111,0,0,266,267,5,110,0,0,267,268,5,116,0,0,268,269,\n        5,95,0,0,269,270,5,115,0,0,270,271,5,99,0,0,271,272,5,97,0,0,272,\n        273,5,110,0,0,273,274,5,95,0,0,274,275,5,100,0,0,275,276,5,105,0,\n        0,276,277,5,114,0,0,277,818,5,115,0,0,278,279,5,100,0,0,279,280,\n        5,111,0,0,280,281,5,110,0,0,281,282,5,116,0,0,282,283,5,95,0,0,283,\n        284,5,115,0,0,284,285,5,99,0,0,285,286,5,97,0,0,286,287,5,110,0,\n        0,287,288,5,95,0,0,288,289,5,102,0,0,289,290,5,105,0,0,290,291,5,\n        108,0,0,291,292,5,101,0,0,292,818,5,115,0,0,293,294,5,100,0,0,294,\n        295,5,111,0,0,295,296,5,110,0,0,296,297,5,116,0,0,297,298,5,95,0,\n        0,298,299,5,115,0,0,299,300,5,99,0,0,300,301,5,97,0,0,301,302,5,\n        110,0,0,302,303,5,95,0,0,303,304,5,102,0,0,304,305,5,105,0,0,305,\n        306,5,114,0,0,306,307,5,109,0,0,307,308,5,119,0,0,308,309,5,97,0,\n        0,309,310,5,114,0,0,310,818,5,101,0,0,311,312,5,100,0,0,312,313,\n        5,111,0,0,313,314,5,110,0,0,314,315,5,116,0,0,315,316,5,95,0,0,316,\n        317,5,115,0,0,317,318,5,99,0,0,318,319,5,97,0,0,319,320,5,110,0,\n        0,320,321,5,95,0,0,321,322,5,116,0,0,322,323,5,111,0,0,323,324,5,\n        111,0,0,324,325,5,108,0,0,325,818,5,115,0,0,326,327,5,100,0,0,327,\n        328,5,111,0,0,328,329,5,110,0,0,329,330,5,116,0,0,330,331,5,95,0,\n        0,331,332,5,115,0,0,332,333,5,99,0,0,333,334,5,97,0,0,334,335,5,\n        110,0,0,335,336,5,95,0,0,336,337,5,118,0,0,337,338,5,111,0,0,338,\n        339,5,108,0,0,339,340,5,117,0,0,340,341,5,109,0,0,341,342,5,101,\n        0,0,342,818,5,115,0,0,343,344,5,101,0,0,344,345,5,110,0,0,345,346,\n        5,97,0,0,346,347,5,98,0,0,347,348,5,108,0,0,348,349,5,101,0,0,349,\n        350,5,95,0,0,350,351,5,97,0,0,351,352,5,110,0,0,352,353,5,100,0,\n        0,353,354,5,95,0,0,354,355,5,108,0,0,355,356,5,111,0,0,356,357,5,\n        99,0,0,357,358,5,107,0,0,358,359,5,95,0,0,359,360,5,118,0,0,360,\n        361,5,109,0,0,361,818,5,120,0,0,362,363,5,101,0,0,363,364,5,110,\n        0,0,364,365,5,97,0,0,365,366,5,98,0,0,366,367,5,108,0,0,367,368,\n        5,101,0,0,368,369,5,95,0,0,369,370,5,109,0,0,370,371,5,111,0,0,371,\n        372,5,117,0,0,372,373,5,115,0,0,373,818,5,101,0,0,374,375,5,101,\n        0,0,375,376,5,110,0,0,376,377,5,97,0,0,377,378,5,98,0,0,378,379,\n        5,108,0,0,379,380,5,101,0,0,380,381,5,95,0,0,381,382,5,116,0,0,382,\n        383,5,111,0,0,383,384,5,117,0,0,384,385,5,99,0,0,385,818,5,104,0,\n        0,386,387,5,101,0,0,387,388,5,120,0,0,388,389,5,116,0,0,389,390,\n        5,114,0,0,390,391,5,97,0,0,391,392,5,95,0,0,392,393,5,107,0,0,393,\n        394,5,101,0,0,394,395,5,114,0,0,395,396,5,110,0,0,396,397,5,101,\n        0,0,397,398,5,108,0,0,398,399,5,95,0,0,399,400,5,118,0,0,400,401,\n        5,101,0,0,401,402,5,114,0,0,402,403,5,115,0,0,403,404,5,105,0,0,\n        404,405,5,111,0,0,405,406,5,110,0,0,406,407,5,95,0,0,407,408,5,115,\n        0,0,408,409,5,116,0,0,409,410,5,114,0,0,410,411,5,105,0,0,411,412,\n        5,110,0,0,412,413,5,103,0,0,413,818,5,115,0,0,414,415,5,102,0,0,\n        415,416,5,111,0,0,416,417,5,108,0,0,417,418,5,100,0,0,418,419,5,\n        95,0,0,419,420,5,108,0,0,420,421,5,105,0,0,421,422,5,110,0,0,422,\n        423,5,117,0,0,423,424,5,120,0,0,424,425,5,95,0,0,425,426,5,107,0,\n        0,426,427,5,101,0,0,427,428,5,114,0,0,428,429,5,110,0,0,429,430,\n        5,101,0,0,430,431,5,108,0,0,431,818,5,115,0,0,432,433,5,102,0,0,\n        433,434,5,111,0,0,434,435,5,108,0,0,435,436,5,108,0,0,436,437,5,\n        111,0,0,437,438,5,119,0,0,438,439,5,95,0,0,439,440,5,115,0,0,440,\n        441,5,121,0,0,441,442,5,109,0,0,442,443,5,108,0,0,443,444,5,105,\n        0,0,444,445,5,110,0,0,445,446,5,107,0,0,446,818,5,115,0,0,447,448,\n        5,102,0,0,448,449,5,111,0,0,449,450,5,110,0,0,450,818,5,116,0,0,\n        451,452,5,104,0,0,452,453,5,105,0,0,453,454,5,100,0,0,454,455,5,\n        101,0,0,455,456,5,117,0,0,456,818,5,105,0,0,457,458,5,105,0,0,458,\n        459,5,99,0,0,459,460,5,111,0,0,460,461,5,110,0,0,461,462,5,115,0,\n        0,462,463,5,95,0,0,463,464,5,100,0,0,464,465,5,105,0,0,465,818,5,\n        114,0,0,466,467,5,108,0,0,467,468,5,105,0,0,468,469,5,110,0,0,469,\n        470,5,117,0,0,470,471,5,120,0,0,471,472,5,95,0,0,472,473,5,112,0,\n        0,473,474,5,114,0,0,474,475,5,101,0,0,475,476,5,102,0,0,476,477,\n        5,105,0,0,477,478,5,120,0,0,478,479,5,101,0,0,479,818,5,115,0,0,\n        480,481,5,108,0,0,481,482,5,111,0,0,482,483,5,103,0,0,483,484,5,\n        95,0,0,484,485,5,108,0,0,485,486,5,101,0,0,486,487,5,118,0,0,487,\n        488,5,101,0,0,488,818,5,108,0,0,489,490,5,109,0,0,490,491,5,97,0,\n        0,491,492,5,120,0,0,492,493,5,95,0,0,493,494,5,116,0,0,494,495,5,\n        97,0,0,495,496,5,103,0,0,496,818,5,115,0,0,497,498,5,109,0,0,498,\n        499,5,111,0,0,499,500,5,117,0,0,500,501,5,115,0,0,501,502,5,101,\n        0,0,502,503,5,95,0,0,503,504,5,115,0,0,504,505,5,105,0,0,505,506,\n        5,122,0,0,506,818,5,101,0,0,507,508,5,109,0,0,508,509,5,111,0,0,\n        509,510,5,117,0,0,510,511,5,115,0,0,511,512,5,101,0,0,512,513,5,\n        95,0,0,513,514,5,115,0,0,514,515,5,112,0,0,515,516,5,101,0,0,516,\n        517,5,101,0,0,517,818,5,100,0,0,518,519,5,114,0,0,519,520,5,101,\n        0,0,520,521,5,115,0,0,521,522,5,111,0,0,522,523,5,108,0,0,523,524,\n        5,117,0,0,524,525,5,116,0,0,525,526,5,105,0,0,526,527,5,111,0,0,\n        527,818,5,110,0,0,528,529,5,115,0,0,529,530,5,99,0,0,530,531,5,97,\n        0,0,531,532,5,110,0,0,532,533,5,95,0,0,533,534,5,97,0,0,534,535,\n        5,108,0,0,535,536,5,108,0,0,536,537,5,95,0,0,537,538,5,108,0,0,538,\n        539,5,105,0,0,539,540,5,110,0,0,540,541,5,117,0,0,541,542,5,120,\n        0,0,542,543,5,95,0,0,543,544,5,107,0,0,544,545,5,101,0,0,545,546,\n        5,114,0,0,546,547,5,110,0,0,547,548,5,101,0,0,548,549,5,108,0,0,\n        549,818,5,115,0,0,550,551,5,115,0,0,551,552,5,99,0,0,552,553,5,97,\n        0,0,553,554,5,110,0,0,554,555,5,95,0,0,555,556,5,100,0,0,556,557,\n        5,101,0,0,557,558,5,108,0,0,558,559,5,97,0,0,559,818,5,121,0,0,560,\n        561,5,115,0,0,561,562,5,99,0,0,562,563,5,97,0,0,563,564,5,110,0,\n        0,564,565,5,95,0,0,565,566,5,100,0,0,566,567,5,114,0,0,567,568,5,\n        105,0,0,568,569,5,118,0,0,569,570,5,101,0,0,570,571,5,114,0,0,571,\n        572,5,95,0,0,572,573,5,100,0,0,573,574,5,105,0,0,574,575,5,114,0,\n        0,575,818,5,115,0,0,576,577,5,115,0,0,577,578,5,99,0,0,578,579,5,\n        97,0,0,579,580,5,110,0,0,580,581,5,102,0,0,581,582,5,111,0,0,582,\n        818,5,114,0,0,583,584,5,115,0,0,584,585,5,99,0,0,585,586,5,114,0,\n        0,586,587,5,101,0,0,587,588,5,101,0,0,588,589,5,110,0,0,589,590,\n        5,115,0,0,590,591,5,97,0,0,591,592,5,118,0,0,592,593,5,101,0,0,593,\n        818,5,114,0,0,594,595,5,115,0,0,595,596,5,101,0,0,596,597,5,108,\n        0,0,597,598,5,101,0,0,598,599,5,99,0,0,599,600,5,116,0,0,600,601,\n        5,105,0,0,601,602,5,111,0,0,602,603,5,110,0,0,603,604,5,95,0,0,604,\n        605,5,98,0,0,605,606,5,105,0,0,606,818,5,103,0,0,607,608,5,115,0,\n        0,608,609,5,101,0,0,609,610,5,108,0,0,610,611,5,101,0,0,611,612,\n        5,99,0,0,612,613,5,116,0,0,613,614,5,105,0,0,614,615,5,111,0,0,615,\n        616,5,110,0,0,616,617,5,95,0,0,617,618,5,115,0,0,618,619,5,109,0,\n        0,619,620,5,97,0,0,620,621,5,108,0,0,621,818,5,108,0,0,622,623,5,\n        115,0,0,623,624,5,104,0,0,624,625,5,111,0,0,625,626,5,119,0,0,626,\n        627,5,116,0,0,627,628,5,111,0,0,628,629,5,111,0,0,629,630,5,108,\n        0,0,630,818,5,115,0,0,631,632,5,115,0,0,632,633,5,104,0,0,633,634,\n        5,117,0,0,634,635,5,116,0,0,635,636,5,100,0,0,636,637,5,111,0,0,\n        637,638,5,119,0,0,638,639,5,110,0,0,639,640,5,95,0,0,640,641,5,97,\n        0,0,641,642,5,102,0,0,642,643,5,116,0,0,643,644,5,101,0,0,644,645,\n        5,114,0,0,645,646,5,95,0,0,646,647,5,116,0,0,647,648,5,105,0,0,648,\n        649,5,109,0,0,649,650,5,101,0,0,650,651,5,111,0,0,651,652,5,117,\n        0,0,652,818,5,116,0,0,653,654,5,115,0,0,654,655,5,109,0,0,655,656,\n        5,97,0,0,656,657,5,108,0,0,657,658,5,108,0,0,658,659,5,95,0,0,659,\n        660,5,105,0,0,660,661,5,99,0,0,661,662,5,111,0,0,662,663,5,110,0,\n        0,663,664,5,95,0,0,664,665,5,115,0,0,665,666,5,105,0,0,666,667,5,\n        122,0,0,667,818,5,101,0,0,668,669,5,115,0,0,669,670,5,112,0,0,670,\n        671,5,111,0,0,671,672,5,111,0,0,672,673,5,102,0,0,673,674,5,95,0,\n        0,674,675,5,111,0,0,675,676,5,115,0,0,676,677,5,120,0,0,677,678,\n        5,95,0,0,678,679,5,118,0,0,679,680,5,101,0,0,680,681,5,114,0,0,681,\n        682,5,115,0,0,682,683,5,105,0,0,683,684,5,111,0,0,684,818,5,110,\n        0,0,685,686,5,115,0,0,686,687,5,117,0,0,687,688,5,112,0,0,688,689,\n        5,112,0,0,689,690,5,111,0,0,690,691,5,114,0,0,691,692,5,116,0,0,\n        692,693,5,95,0,0,693,694,5,103,0,0,694,695,5,122,0,0,695,696,5,105,\n        0,0,696,697,5,112,0,0,697,698,5,112,0,0,698,699,5,101,0,0,699,700,\n        5,100,0,0,700,701,5,95,0,0,701,702,5,108,0,0,702,703,5,111,0,0,703,\n        704,5,97,0,0,704,705,5,100,0,0,705,706,5,101,0,0,706,707,5,114,0,\n        0,707,818,5,115,0,0,708,709,5,116,0,0,709,710,5,101,0,0,710,711,\n        5,120,0,0,711,712,5,116,0,0,712,713,5,109,0,0,713,714,5,111,0,0,\n        714,715,5,100,0,0,715,818,5,101,0,0,716,717,5,116,0,0,717,718,5,\n        101,0,0,718,719,5,120,0,0,719,720,5,116,0,0,720,721,5,111,0,0,721,\n        722,5,110,0,0,722,723,5,108,0,0,723,818,5,121,0,0,724,725,5,116,\n        0,0,725,726,5,105,0,0,726,727,5,109,0,0,727,728,5,101,0,0,728,729,\n        5,111,0,0,729,730,5,117,0,0,730,818,5,116,0,0,731,732,5,117,0,0,\n        732,733,5,101,0,0,733,734,5,102,0,0,734,735,5,105,0,0,735,736,5,\n        95,0,0,736,737,5,100,0,0,737,738,5,101,0,0,738,739,5,101,0,0,739,\n        740,5,112,0,0,740,741,5,95,0,0,741,742,5,108,0,0,742,743,5,101,0,\n        0,743,744,5,103,0,0,744,745,5,97,0,0,745,746,5,99,0,0,746,747,5,\n        121,0,0,747,748,5,95,0,0,748,749,5,115,0,0,749,750,5,99,0,0,750,\n        751,5,97,0,0,751,818,5,110,0,0,752,753,5,117,0,0,753,754,5,115,0,\n        0,754,755,5,101,0,0,755,756,5,95,0,0,756,757,5,103,0,0,757,758,5,\n        114,0,0,758,759,5,97,0,0,759,760,5,112,0,0,760,761,5,104,0,0,761,\n        762,5,105,0,0,762,763,5,99,0,0,763,764,5,115,0,0,764,765,5,95,0,\n        0,765,766,5,102,0,0,766,767,5,111,0,0,767,818,5,114,0,0,768,769,\n        5,117,0,0,769,770,5,115,0,0,770,771,5,101,0,0,771,772,5,95,0,0,772,\n        773,5,110,0,0,773,774,5,118,0,0,774,775,5,114,0,0,775,776,5,97,0,\n        0,776,818,5,109,0,0,777,778,5,119,0,0,778,779,5,105,0,0,779,780,\n        5,110,0,0,780,781,5,100,0,0,781,782,5,111,0,0,782,783,5,119,0,0,\n        783,784,5,115,0,0,784,785,5,95,0,0,785,786,5,114,0,0,786,787,5,101,\n        0,0,787,788,5,99,0,0,788,789,5,111,0,0,789,790,5,118,0,0,790,791,\n        5,101,0,0,791,792,5,114,0,0,792,793,5,121,0,0,793,794,5,95,0,0,794,\n        795,5,102,0,0,795,796,5,105,0,0,796,797,5,108,0,0,797,798,5,101,\n        0,0,798,818,5,115,0,0,799,800,5,119,0,0,800,801,5,114,0,0,801,802,\n        5,105,0,0,802,803,5,116,0,0,803,804,5,101,0,0,804,805,5,95,0,0,805,\n        806,5,115,0,0,806,807,5,121,0,0,807,808,5,115,0,0,808,809,5,116,\n        0,0,809,810,5,101,0,0,810,811,5,109,0,0,811,812,5,100,0,0,812,813,\n        5,95,0,0,813,814,5,118,0,0,814,815,5,97,0,0,815,816,5,114,0,0,816,\n        818,5,115,0,0,817,93,1,0,0,0,817,107,1,0,0,0,817,122,1,0,0,0,817,\n        128,1,0,0,0,817,140,1,0,0,0,817,153,1,0,0,0,817,163,1,0,0,0,817,\n        180,1,0,0,0,817,195,1,0,0,0,817,211,1,0,0,0,817,230,1,0,0,0,817,\n        246,1,0,0,0,817,264,1,0,0,0,817,278,1,0,0,0,817,293,1,0,0,0,817,\n        311,1,0,0,0,817,326,1,0,0,0,817,343,1,0,0,0,817,362,1,0,0,0,817,\n        374,1,0,0,0,817,386,1,0,0,0,817,414,1,0,0,0,817,432,1,0,0,0,817,\n        447,1,0,0,0,817,451,1,0,0,0,817,457,1,0,0,0,817,466,1,0,0,0,817,\n        480,1,0,0,0,817,489,1,0,0,0,817,497,1,0,0,0,817,507,1,0,0,0,817,\n        518,1,0,0,0,817,528,1,0,0,0,817,550,1,0,0,0,817,560,1,0,0,0,817,\n        576,1,0,0,0,817,583,1,0,0,0,817,594,1,0,0,0,817,607,1,0,0,0,817,\n        622,1,0,0,0,817,631,1,0,0,0,817,653,1,0,0,0,817,668,1,0,0,0,817,\n        685,1,0,0,0,817,708,1,0,0,0,817,716,1,0,0,0,817,724,1,0,0,0,817,\n        731,1,0,0,0,817,752,1,0,0,0,817,768,1,0,0,0,817,777,1,0,0,0,817,\n        799,1,0,0,0,818,822,1,0,0,0,819,821,8,1,0,0,820,819,1,0,0,0,821,\n        824,1,0,0,0,822,820,1,0,0,0,822,823,1,0,0,0,823,826,1,0,0,0,824,\n        822,1,0,0,0,825,827,3,4,1,0,826,825,1,0,0,0,826,827,1,0,0,0,827,\n        828,1,0,0,0,828,829,6,4,0,0,829,11,1,0,0,0,830,833,3,14,6,0,831,\n        833,3,16,7,0,832,830,1,0,0,0,832,831,1,0,0,0,833,13,1,0,0,0,834,\n        835,5,109,0,0,835,836,5,101,0,0,836,837,5,110,0,0,837,838,5,117,\n        0,0,838,839,5,101,0,0,839,840,5,110,0,0,840,841,5,116,0,0,841,842,\n        5,114,0,0,842,843,5,121,0,0,843,15,1,0,0,0,844,845,5,115,0,0,845,\n        846,5,117,0,0,846,847,5,98,0,0,847,848,5,109,0,0,848,849,5,101,0,\n        0,849,850,5,110,0,0,850,851,5,117,0,0,851,852,5,101,0,0,852,853,\n        5,110,0,0,853,854,5,116,0,0,854,855,5,114,0,0,855,856,5,121,0,0,\n        856,17,1,0,0,0,857,858,5,118,0,0,858,859,5,111,0,0,859,860,5,108,\n        0,0,860,861,5,117,0,0,861,862,5,109,0,0,862,863,5,101,0,0,863,19,\n        1,0,0,0,864,865,5,108,0,0,865,866,5,111,0,0,866,867,5,97,0,0,867,\n        868,5,100,0,0,868,869,5,101,0,0,869,870,5,114,0,0,870,21,1,0,0,0,\n        871,872,5,105,0,0,872,873,5,110,0,0,873,874,5,105,0,0,874,875,5,\n        116,0,0,875,876,5,114,0,0,876,877,5,100,0,0,877,23,1,0,0,0,878,879,\n        5,105,0,0,879,880,5,99,0,0,880,881,5,111,0,0,881,882,5,110,0,0,882,\n        25,1,0,0,0,883,884,5,111,0,0,884,885,5,115,0,0,885,886,5,116,0,0,\n        886,887,5,121,0,0,887,888,5,112,0,0,888,889,5,101,0,0,889,890,1,\n        0,0,0,890,891,3,2,0,0,891,892,1,0,0,0,892,893,6,12,1,0,893,27,1,\n        0,0,0,894,895,5,103,0,0,895,896,5,114,0,0,896,897,5,97,0,0,897,898,\n        5,112,0,0,898,899,5,104,0,0,899,900,5,105,0,0,900,901,5,99,0,0,901,\n        902,5,115,0,0,902,903,1,0,0,0,903,904,3,2,0,0,904,905,1,0,0,0,905,\n        906,6,13,1,0,906,29,1,0,0,0,907,908,5,111,0,0,908,909,5,112,0,0,\n        909,910,5,116,0,0,910,911,5,105,0,0,911,912,5,111,0,0,912,913,5,\n        110,0,0,913,914,5,115,0,0,914,31,1,0,0,0,915,916,5,97,0,0,916,917,\n        5,100,0,0,917,918,5,100,0,0,918,919,5,95,0,0,919,920,5,111,0,0,920,\n        921,5,112,0,0,921,922,5,116,0,0,922,923,5,105,0,0,923,924,5,111,\n        0,0,924,925,5,110,0,0,925,926,5,115,0,0,926,33,1,0,0,0,927,928,5,\n        102,0,0,928,929,5,105,0,0,929,930,5,114,0,0,930,931,5,109,0,0,931,\n        932,5,119,0,0,932,933,5,97,0,0,933,934,5,114,0,0,934,935,5,101,0,\n        0,935,936,5,95,0,0,936,937,5,98,0,0,937,938,5,111,0,0,938,939,5,\n        111,0,0,939,940,5,116,0,0,940,941,5,110,0,0,941,942,5,117,0,0,942,\n        943,5,109,0,0,943,35,1,0,0,0,944,945,5,100,0,0,945,946,5,105,0,0,\n        946,947,5,115,0,0,947,948,5,97,0,0,948,949,5,98,0,0,949,950,5,108,\n        0,0,950,951,5,101,0,0,951,952,5,100,0,0,952,37,1,0,0,0,953,954,5,\n        105,0,0,954,955,5,110,0,0,955,956,5,99,0,0,956,957,5,108,0,0,957,\n        958,5,117,0,0,958,959,5,100,0,0,959,960,5,101,0,0,960,39,1,0,0,0,\n        961,962,5,123,0,0,962,41,1,0,0,0,963,964,5,125,0,0,964,43,1,0,0,\n        0,965,967,3,46,22,0,966,965,1,0,0,0,967,968,1,0,0,0,968,966,1,0,\n        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,\n        0,972,976,3,50,24,0,973,976,3,52,25,0,974,976,3,54,26,0,975,972,\n        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,\n        39,0,0,978,980,8,1,0,0,979,978,1,0,0,0,980,981,1,0,0,0,981,979,1,\n        0,0,0,981,982,1,0,0,0,982,983,1,0,0,0,983,984,5,39,0,0,984,51,1,\n        0,0,0,985,987,5,34,0,0,986,988,8,1,0,0,987,986,1,0,0,0,988,989,1,\n        0,0,0,989,987,1,0,0,0,989,990,1,0,0,0,990,991,1,0,0,0,991,992,5,\n        34,0,0,992,53,1,0,0,0,993,995,8,3,0,0,994,993,1,0,0,0,995,996,1,\n        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,\n        0,0,999,1000,5,97,0,0,1000,1001,5,99,0,0,1001,1002,5,79,0,0,1002,\n        1024,5,83,0,0,1003,1004,5,76,0,0,1004,1005,5,105,0,0,1005,1006,5,\n        110,0,0,1006,1007,5,117,0,0,1007,1024,5,120,0,0,1008,1009,5,69,0,\n        0,1009,1010,5,76,0,0,1010,1011,5,73,0,0,1011,1012,5,76,0,0,1012,\n        1024,5,79,0,0,1013,1014,5,87,0,0,1014,1015,5,105,0,0,1015,1016,5,\n        110,0,0,1016,1017,5,100,0,0,1017,1018,5,111,0,0,1018,1019,5,119,\n        0,0,1019,1024,5,115,0,0,1020,1021,5,88,0,0,1021,1022,5,79,0,0,1022,\n        1024,5,77,0,0,1023,998,1,0,0,0,1023,1003,1,0,0,0,1023,1008,1,0,0,\n        0,1023,1013,1,0,0,0,1023,1020,1,0,0,0,1024,1025,1,0,0,0,1025,1026,\n        6,27,2,0,1026,57,1,0,0,0,1027,1028,5,111,0,0,1028,1033,5,110,0,0,\n        1029,1030,5,111,0,0,1030,1031,5,102,0,0,1031,1033,5,102,0,0,1032,\n        1027,1,0,0,0,1032,1029,1,0,0,0,1033,1034,1,0,0,0,1034,1035,6,28,\n        2,0,1035,59,1,0,0,0,18,0,1,63,68,75,85,89,817,822,826,832,968,975,\n        981,989,996,1023,1032,3,6,0,0,5,1,0,4,0,0\n    ]\n\nclass RefindConfigLexer(Lexer):\n\n    atn = ATNDeserializer().deserialize(serializedATN())\n\n    decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]\n\n    STRICT_PARAMETER_MODE = 1\n\n    WHITESPACE = 1\n    NEWLINE = 2\n    EMPTY = 3\n    COMMENT = 4\n    IGNORED_OPTION = 5\n    MENU_ENTRY = 6\n    VOLUME = 7\n    LOADER = 8\n    INITRD = 9\n    ICON = 10\n    OS_TYPE = 11\n    GRAPHICS = 12\n    BOOT_OPTIONS = 13\n    ADD_BOOT_OPTIONS = 14\n    FIRMWARE_BOOTNUM = 15\n    DISABLED = 16\n    INCLUDE = 17\n    OPEN_BRACE = 18\n    CLOSE_BRACE = 19\n    HEX_INTEGER = 20\n    STRING = 21\n    OS_TYPE_PARAMETER = 22\n    GRAPHICS_PARAMETER = 23\n\n    channelNames = [ u\"DEFAULT_TOKEN_CHANNEL\", u\"HIDDEN\" ]\n\n    modeNames = [ \"DEFAULT_MODE\", \"STRICT_PARAMETER_MODE\" ]\n\n    literalNames = [ \"<INVALID>\",\n            \"'volume'\", \"'loader'\", \"'initrd'\", \"'icon'\", \"'options'\", \"'add_options'\", \n            \"'firmware_bootnum'\", \"'disabled'\", \"'include'\", \"'{'\", \"'}'\" ]\n\n    symbolicNames = [ \"<INVALID>\",\n            \"WHITESPACE\", \"NEWLINE\", \"EMPTY\", \"COMMENT\", \"IGNORED_OPTION\", \n            \"MENU_ENTRY\", \"VOLUME\", \"LOADER\", \"INITRD\", \"ICON\", \"OS_TYPE\", \n            \"GRAPHICS\", \"BOOT_OPTIONS\", \"ADD_BOOT_OPTIONS\", \"FIRMWARE_BOOTNUM\", \n            \"DISABLED\", \"INCLUDE\", \"OPEN_BRACE\", \"CLOSE_BRACE\", \"HEX_INTEGER\", \n            \"STRING\", \"OS_TYPE_PARAMETER\", \"GRAPHICS_PARAMETER\" ]\n\n    ruleNames = [ \"WHITESPACE\", \"NEWLINE\", \"EMPTY\", \"COMMENT\", \"IGNORED_OPTION\", \n                  \"MENU_ENTRY\", \"MAIN_MENU_ENTRY\", \"SUB_MENU_ENTRY\", \"VOLUME\", \n                  \"LOADER\", \"INITRD\", \"ICON\", \"OS_TYPE\", \"GRAPHICS\", \"BOOT_OPTIONS\", \n                  \"ADD_BOOT_OPTIONS\", \"FIRMWARE_BOOTNUM\", \"DISABLED\", \"INCLUDE\", \n                  \"OPEN_BRACE\", \"CLOSE_BRACE\", \"HEX_INTEGER\", \"HEX_DIGIT\", \n                  \"STRING\", \"SINGLE_QUOTED_STRING\", \"DOUBLE_QUOTED_STRING\", \n                  \"UNQUOTED_STRING\", \"OS_TYPE_PARAMETER\", \"GRAPHICS_PARAMETER\" ]\n\n    grammarFileName = \"RefindConfigLexer.g4\"\n\n    def __init__(self, input=None, output:TextIO = sys.stdout):\n        super().__init__(input, output)\n        self.checkVersion(\"4.13.1\")\n        self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())\n        self._actions = None\n        self._predicates = None\n\n\n"
  },
  {
    "path": "src/refind_btrfs/boot/antlr4/RefindConfigLexer.tokens",
    "content": "WHITESPACE=1\nNEWLINE=2\nEMPTY=3\nCOMMENT=4\nIGNORED_OPTION=5\nMENU_ENTRY=6\nVOLUME=7\nLOADER=8\nINITRD=9\nICON=10\nOS_TYPE=11\nGRAPHICS=12\nBOOT_OPTIONS=13\nADD_BOOT_OPTIONS=14\nFIRMWARE_BOOTNUM=15\nDISABLED=16\nINCLUDE=17\nOPEN_BRACE=18\nCLOSE_BRACE=19\nHEX_INTEGER=20\nSTRING=21\nOS_TYPE_PARAMETER=22\nGRAPHICS_PARAMETER=23\n'volume'=7\n'loader'=8\n'initrd'=9\n'icon'=10\n'options'=13\n'add_options'=14\n'firmware_bootnum'=15\n'disabled'=16\n'include'=17\n'{'=18\n'}'=19\n"
  },
  {
    "path": "src/refind_btrfs/boot/antlr4/RefindConfigParser.g4",
    "content": "/*\nSPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n\nSPDX-License-Identifier: GPL-3.0-or-later\n\nrefind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\nparser grammar RefindConfigParser;\n\noptions { tokenVocab=RefindConfigLexer; }\n\nrefind : config_option* EOF ;\n\nconfig_option\n    : boot_stanza\n    | include\n    ;\n\n// \"menuentry\" section\nboot_stanza : menu_entry OPEN_BRACE main_option+ CLOSE_BRACE ;\n\nmenu_entry : MENU_ENTRY STRING ;\nmain_option\n    : volume\n    | loader\n    | main_initrd\n    | icon\n    | os_type\n    | graphics\n    | main_boot_options\n    | firmware_bootnum\n    | disabled\n    | sub_menu\n    ;\n\nvolume : VOLUME STRING ;\nloader : LOADER STRING ;\nmain_initrd : INITRD STRING ;\nicon : ICON STRING ;\nos_type : OS_TYPE OS_TYPE_PARAMETER ;\ngraphics : GRAPHICS GRAPHICS_PARAMETER ;\nmain_boot_options : BOOT_OPTIONS STRING ;\nfirmware_bootnum: FIRMWARE_BOOTNUM HEX_INTEGER ;\ndisabled : DISABLED;\n\n// \"submenuentry\" section\nsub_menu : menu_entry OPEN_BRACE sub_option+ CLOSE_BRACE ;\n\nsub_option\n    : loader\n    | sub_initrd\n    | graphics\n    | sub_boot_options\n    | add_boot_options\n    | disabled\n    ;\n\nsub_initrd : INITRD STRING? ;\nsub_boot_options : BOOT_OPTIONS STRING? ;\nadd_boot_options : ADD_BOOT_OPTIONS STRING ;\n\n// \"include\" section\ninclude : INCLUDE STRING ;\n"
  },
  {
    "path": "src/refind_btrfs/boot/antlr4/RefindConfigParser.interp",
    "content": "token literal names:\nnull\nnull\nnull\nnull\nnull\nnull\nnull\n'volume'\n'loader'\n'initrd'\n'icon'\nnull\nnull\n'options'\n'add_options'\n'firmware_bootnum'\n'disabled'\n'include'\n'{'\n'}'\nnull\nnull\nnull\nnull\n\ntoken symbolic names:\nnull\nWHITESPACE\nNEWLINE\nEMPTY\nCOMMENT\nIGNORED_OPTION\nMENU_ENTRY\nVOLUME\nLOADER\nINITRD\nICON\nOS_TYPE\nGRAPHICS\nBOOT_OPTIONS\nADD_BOOT_OPTIONS\nFIRMWARE_BOOTNUM\nDISABLED\nINCLUDE\nOPEN_BRACE\nCLOSE_BRACE\nHEX_INTEGER\nSTRING\nOS_TYPE_PARAMETER\nGRAPHICS_PARAMETER\n\nrule names:\nrefind\nconfig_option\nboot_stanza\nmenu_entry\nmain_option\nvolume\nloader\nmain_initrd\nicon\nos_type\ngraphics\nmain_boot_options\nfirmware_bootnum\ndisabled\nsub_menu\nsub_option\nsub_initrd\nsub_boot_options\nadd_boot_options\ninclude\n\n\natn:\n[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]"
  },
  {
    "path": "src/refind_btrfs/boot/antlr4/RefindConfigParser.py",
    "content": "# Generated from c:/Users/Luka/Projects/Python/refind-btrfs/src/refind_btrfs/boot/antlr4/RefindConfigParser.g4 by ANTLR 4.13.1\n# encoding: utf-8\nfrom antlr4 import *\nfrom io import StringIO\nimport sys\nif sys.version_info[1] > 5:\n\tfrom typing import TextIO\nelse:\n\tfrom typing.io import TextIO\n\ndef serializedATN():\n    return [\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        12,1,12,1,13,1,13,1,14,1,14,1,14,4,14,106,8,14,11,14,12,14,107,1,\n        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,\n        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,\n        1,19,0,0,20,0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        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,\n        102,103,3,6,3,0,103,105,5,18,0,0,104,106,3,30,15,0,105,104,1,0,0,\n        0,106,107,1,0,0,0,107,105,1,0,0,0,107,108,1,0,0,0,108,109,1,0,0,\n        0,109,110,5,19,0,0,110,29,1,0,0,0,111,118,3,12,6,0,112,118,3,32,\n        16,0,113,118,3,20,10,0,114,118,3,34,17,0,115,118,3,36,18,0,116,118,\n        3,26,13,0,117,111,1,0,0,0,117,112,1,0,0,0,117,113,1,0,0,0,117,114,\n        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,\n        9,0,0,120,122,5,21,0,0,121,120,1,0,0,0,121,122,1,0,0,0,122,33,1,\n        0,0,0,123,125,5,13,0,0,124,126,5,21,0,0,125,124,1,0,0,0,125,126,\n        1,0,0,0,126,35,1,0,0,0,127,128,5,14,0,0,128,129,5,21,0,0,129,37,\n        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,\n        57,74,107,117,121,125\n    ]\n\nclass RefindConfigParser ( Parser ):\n\n    grammarFileName = \"RefindConfigParser.g4\"\n\n    atn = ATNDeserializer().deserialize(serializedATN())\n\n    decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]\n\n    sharedContextCache = PredictionContextCache()\n\n    literalNames = [ \"<INVALID>\", \"<INVALID>\", \"<INVALID>\", \"<INVALID>\", \n                     \"<INVALID>\", \"<INVALID>\", \"<INVALID>\", \"'volume'\", \n                     \"'loader'\", \"'initrd'\", \"'icon'\", \"<INVALID>\", \"<INVALID>\", \n                     \"'options'\", \"'add_options'\", \"'firmware_bootnum'\", \n                     \"'disabled'\", \"'include'\", \"'{'\", \"'}'\" ]\n\n    symbolicNames = [ \"<INVALID>\", \"WHITESPACE\", \"NEWLINE\", \"EMPTY\", \"COMMENT\", \n                      \"IGNORED_OPTION\", \"MENU_ENTRY\", \"VOLUME\", \"LOADER\", \n                      \"INITRD\", \"ICON\", \"OS_TYPE\", \"GRAPHICS\", \"BOOT_OPTIONS\", \n                      \"ADD_BOOT_OPTIONS\", \"FIRMWARE_BOOTNUM\", \"DISABLED\", \n                      \"INCLUDE\", \"OPEN_BRACE\", \"CLOSE_BRACE\", \"HEX_INTEGER\", \n                      \"STRING\", \"OS_TYPE_PARAMETER\", \"GRAPHICS_PARAMETER\" ]\n\n    RULE_refind = 0\n    RULE_config_option = 1\n    RULE_boot_stanza = 2\n    RULE_menu_entry = 3\n    RULE_main_option = 4\n    RULE_volume = 5\n    RULE_loader = 6\n    RULE_main_initrd = 7\n    RULE_icon = 8\n    RULE_os_type = 9\n    RULE_graphics = 10\n    RULE_main_boot_options = 11\n    RULE_firmware_bootnum = 12\n    RULE_disabled = 13\n    RULE_sub_menu = 14\n    RULE_sub_option = 15\n    RULE_sub_initrd = 16\n    RULE_sub_boot_options = 17\n    RULE_add_boot_options = 18\n    RULE_include = 19\n\n    ruleNames =  [ \"refind\", \"config_option\", \"boot_stanza\", \"menu_entry\", \n                   \"main_option\", \"volume\", \"loader\", \"main_initrd\", \"icon\", \n                   \"os_type\", \"graphics\", \"main_boot_options\", \"firmware_bootnum\", \n                   \"disabled\", \"sub_menu\", \"sub_option\", \"sub_initrd\", \"sub_boot_options\", \n                   \"add_boot_options\", \"include\" ]\n\n    EOF = Token.EOF\n    WHITESPACE=1\n    NEWLINE=2\n    EMPTY=3\n    COMMENT=4\n    IGNORED_OPTION=5\n    MENU_ENTRY=6\n    VOLUME=7\n    LOADER=8\n    INITRD=9\n    ICON=10\n    OS_TYPE=11\n    GRAPHICS=12\n    BOOT_OPTIONS=13\n    ADD_BOOT_OPTIONS=14\n    FIRMWARE_BOOTNUM=15\n    DISABLED=16\n    INCLUDE=17\n    OPEN_BRACE=18\n    CLOSE_BRACE=19\n    HEX_INTEGER=20\n    STRING=21\n    OS_TYPE_PARAMETER=22\n    GRAPHICS_PARAMETER=23\n\n    def __init__(self, input:TokenStream, output:TextIO = sys.stdout):\n        super().__init__(input, output)\n        self.checkVersion(\"4.13.1\")\n        self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache)\n        self._predicates = None\n\n\n\n\n    class RefindContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def EOF(self):\n            return self.getToken(RefindConfigParser.EOF, 0)\n\n        def config_option(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(RefindConfigParser.Config_optionContext)\n            else:\n                return self.getTypedRuleContext(RefindConfigParser.Config_optionContext,i)\n\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_refind\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitRefind\" ):\n                return visitor.visitRefind(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def refind(self):\n\n        localctx = RefindConfigParser.RefindContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 0, self.RULE_refind)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 43\n            self._errHandler.sync(self)\n            _la = self._input.LA(1)\n            while _la==6 or _la==17:\n                self.state = 40\n                self.config_option()\n                self.state = 45\n                self._errHandler.sync(self)\n                _la = self._input.LA(1)\n\n            self.state = 46\n            self.match(RefindConfigParser.EOF)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class Config_optionContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def boot_stanza(self):\n            return self.getTypedRuleContext(RefindConfigParser.Boot_stanzaContext,0)\n\n\n        def include(self):\n            return self.getTypedRuleContext(RefindConfigParser.IncludeContext,0)\n\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_config_option\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitConfig_option\" ):\n                return visitor.visitConfig_option(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def config_option(self):\n\n        localctx = RefindConfigParser.Config_optionContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 2, self.RULE_config_option)\n        try:\n            self.state = 50\n            self._errHandler.sync(self)\n            token = self._input.LA(1)\n            if token in [6]:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 48\n                self.boot_stanza()\n                pass\n            elif token in [17]:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 49\n                self.include()\n                pass\n            else:\n                raise NoViableAltException(self)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class Boot_stanzaContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def menu_entry(self):\n            return self.getTypedRuleContext(RefindConfigParser.Menu_entryContext,0)\n\n\n        def OPEN_BRACE(self):\n            return self.getToken(RefindConfigParser.OPEN_BRACE, 0)\n\n        def CLOSE_BRACE(self):\n            return self.getToken(RefindConfigParser.CLOSE_BRACE, 0)\n\n        def main_option(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(RefindConfigParser.Main_optionContext)\n            else:\n                return self.getTypedRuleContext(RefindConfigParser.Main_optionContext,i)\n\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_boot_stanza\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitBoot_stanza\" ):\n                return visitor.visitBoot_stanza(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def boot_stanza(self):\n\n        localctx = RefindConfigParser.Boot_stanzaContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 4, self.RULE_boot_stanza)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 52\n            self.menu_entry()\n            self.state = 53\n            self.match(RefindConfigParser.OPEN_BRACE)\n            self.state = 55 \n            self._errHandler.sync(self)\n            _la = self._input.LA(1)\n            while True:\n                self.state = 54\n                self.main_option()\n                self.state = 57 \n                self._errHandler.sync(self)\n                _la = self._input.LA(1)\n                if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & 114624) != 0)):\n                    break\n\n            self.state = 59\n            self.match(RefindConfigParser.CLOSE_BRACE)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class Menu_entryContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def MENU_ENTRY(self):\n            return self.getToken(RefindConfigParser.MENU_ENTRY, 0)\n\n        def STRING(self):\n            return self.getToken(RefindConfigParser.STRING, 0)\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_menu_entry\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitMenu_entry\" ):\n                return visitor.visitMenu_entry(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def menu_entry(self):\n\n        localctx = RefindConfigParser.Menu_entryContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 6, self.RULE_menu_entry)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 61\n            self.match(RefindConfigParser.MENU_ENTRY)\n            self.state = 62\n            self.match(RefindConfigParser.STRING)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class Main_optionContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def volume(self):\n            return self.getTypedRuleContext(RefindConfigParser.VolumeContext,0)\n\n\n        def loader(self):\n            return self.getTypedRuleContext(RefindConfigParser.LoaderContext,0)\n\n\n        def main_initrd(self):\n            return self.getTypedRuleContext(RefindConfigParser.Main_initrdContext,0)\n\n\n        def icon(self):\n            return self.getTypedRuleContext(RefindConfigParser.IconContext,0)\n\n\n        def os_type(self):\n            return self.getTypedRuleContext(RefindConfigParser.Os_typeContext,0)\n\n\n        def graphics(self):\n            return self.getTypedRuleContext(RefindConfigParser.GraphicsContext,0)\n\n\n        def main_boot_options(self):\n            return self.getTypedRuleContext(RefindConfigParser.Main_boot_optionsContext,0)\n\n\n        def firmware_bootnum(self):\n            return self.getTypedRuleContext(RefindConfigParser.Firmware_bootnumContext,0)\n\n\n        def disabled(self):\n            return self.getTypedRuleContext(RefindConfigParser.DisabledContext,0)\n\n\n        def sub_menu(self):\n            return self.getTypedRuleContext(RefindConfigParser.Sub_menuContext,0)\n\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_main_option\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitMain_option\" ):\n                return visitor.visitMain_option(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def main_option(self):\n\n        localctx = RefindConfigParser.Main_optionContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 8, self.RULE_main_option)\n        try:\n            self.state = 74\n            self._errHandler.sync(self)\n            token = self._input.LA(1)\n            if token in [7]:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 64\n                self.volume()\n                pass\n            elif token in [8]:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 65\n                self.loader()\n                pass\n            elif token in [9]:\n                self.enterOuterAlt(localctx, 3)\n                self.state = 66\n                self.main_initrd()\n                pass\n            elif token in [10]:\n                self.enterOuterAlt(localctx, 4)\n                self.state = 67\n                self.icon()\n                pass\n            elif token in [11]:\n                self.enterOuterAlt(localctx, 5)\n                self.state = 68\n                self.os_type()\n                pass\n            elif token in [12]:\n                self.enterOuterAlt(localctx, 6)\n                self.state = 69\n                self.graphics()\n                pass\n            elif token in [13]:\n                self.enterOuterAlt(localctx, 7)\n                self.state = 70\n                self.main_boot_options()\n                pass\n            elif token in [15]:\n                self.enterOuterAlt(localctx, 8)\n                self.state = 71\n                self.firmware_bootnum()\n                pass\n            elif token in [16]:\n                self.enterOuterAlt(localctx, 9)\n                self.state = 72\n                self.disabled()\n                pass\n            elif token in [6]:\n                self.enterOuterAlt(localctx, 10)\n                self.state = 73\n                self.sub_menu()\n                pass\n            else:\n                raise NoViableAltException(self)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class VolumeContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def VOLUME(self):\n            return self.getToken(RefindConfigParser.VOLUME, 0)\n\n        def STRING(self):\n            return self.getToken(RefindConfigParser.STRING, 0)\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_volume\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitVolume\" ):\n                return visitor.visitVolume(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def volume(self):\n\n        localctx = RefindConfigParser.VolumeContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 10, self.RULE_volume)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 76\n            self.match(RefindConfigParser.VOLUME)\n            self.state = 77\n            self.match(RefindConfigParser.STRING)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class LoaderContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def LOADER(self):\n            return self.getToken(RefindConfigParser.LOADER, 0)\n\n        def STRING(self):\n            return self.getToken(RefindConfigParser.STRING, 0)\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_loader\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitLoader\" ):\n                return visitor.visitLoader(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def loader(self):\n\n        localctx = RefindConfigParser.LoaderContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 12, self.RULE_loader)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 79\n            self.match(RefindConfigParser.LOADER)\n            self.state = 80\n            self.match(RefindConfigParser.STRING)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class Main_initrdContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def INITRD(self):\n            return self.getToken(RefindConfigParser.INITRD, 0)\n\n        def STRING(self):\n            return self.getToken(RefindConfigParser.STRING, 0)\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_main_initrd\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitMain_initrd\" ):\n                return visitor.visitMain_initrd(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def main_initrd(self):\n\n        localctx = RefindConfigParser.Main_initrdContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 14, self.RULE_main_initrd)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 82\n            self.match(RefindConfigParser.INITRD)\n            self.state = 83\n            self.match(RefindConfigParser.STRING)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class IconContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def ICON(self):\n            return self.getToken(RefindConfigParser.ICON, 0)\n\n        def STRING(self):\n            return self.getToken(RefindConfigParser.STRING, 0)\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_icon\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitIcon\" ):\n                return visitor.visitIcon(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def icon(self):\n\n        localctx = RefindConfigParser.IconContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 16, self.RULE_icon)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 85\n            self.match(RefindConfigParser.ICON)\n            self.state = 86\n            self.match(RefindConfigParser.STRING)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class Os_typeContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def OS_TYPE(self):\n            return self.getToken(RefindConfigParser.OS_TYPE, 0)\n\n        def OS_TYPE_PARAMETER(self):\n            return self.getToken(RefindConfigParser.OS_TYPE_PARAMETER, 0)\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_os_type\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitOs_type\" ):\n                return visitor.visitOs_type(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def os_type(self):\n\n        localctx = RefindConfigParser.Os_typeContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 18, self.RULE_os_type)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 88\n            self.match(RefindConfigParser.OS_TYPE)\n            self.state = 89\n            self.match(RefindConfigParser.OS_TYPE_PARAMETER)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class GraphicsContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def GRAPHICS(self):\n            return self.getToken(RefindConfigParser.GRAPHICS, 0)\n\n        def GRAPHICS_PARAMETER(self):\n            return self.getToken(RefindConfigParser.GRAPHICS_PARAMETER, 0)\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_graphics\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitGraphics\" ):\n                return visitor.visitGraphics(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def graphics(self):\n\n        localctx = RefindConfigParser.GraphicsContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 20, self.RULE_graphics)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 91\n            self.match(RefindConfigParser.GRAPHICS)\n            self.state = 92\n            self.match(RefindConfigParser.GRAPHICS_PARAMETER)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class Main_boot_optionsContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def BOOT_OPTIONS(self):\n            return self.getToken(RefindConfigParser.BOOT_OPTIONS, 0)\n\n        def STRING(self):\n            return self.getToken(RefindConfigParser.STRING, 0)\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_main_boot_options\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitMain_boot_options\" ):\n                return visitor.visitMain_boot_options(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def main_boot_options(self):\n\n        localctx = RefindConfigParser.Main_boot_optionsContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 22, self.RULE_main_boot_options)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 94\n            self.match(RefindConfigParser.BOOT_OPTIONS)\n            self.state = 95\n            self.match(RefindConfigParser.STRING)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class Firmware_bootnumContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def FIRMWARE_BOOTNUM(self):\n            return self.getToken(RefindConfigParser.FIRMWARE_BOOTNUM, 0)\n\n        def HEX_INTEGER(self):\n            return self.getToken(RefindConfigParser.HEX_INTEGER, 0)\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_firmware_bootnum\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitFirmware_bootnum\" ):\n                return visitor.visitFirmware_bootnum(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def firmware_bootnum(self):\n\n        localctx = RefindConfigParser.Firmware_bootnumContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 24, self.RULE_firmware_bootnum)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 97\n            self.match(RefindConfigParser.FIRMWARE_BOOTNUM)\n            self.state = 98\n            self.match(RefindConfigParser.HEX_INTEGER)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class DisabledContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def DISABLED(self):\n            return self.getToken(RefindConfigParser.DISABLED, 0)\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_disabled\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitDisabled\" ):\n                return visitor.visitDisabled(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def disabled(self):\n\n        localctx = RefindConfigParser.DisabledContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 26, self.RULE_disabled)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 100\n            self.match(RefindConfigParser.DISABLED)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class Sub_menuContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def menu_entry(self):\n            return self.getTypedRuleContext(RefindConfigParser.Menu_entryContext,0)\n\n\n        def OPEN_BRACE(self):\n            return self.getToken(RefindConfigParser.OPEN_BRACE, 0)\n\n        def CLOSE_BRACE(self):\n            return self.getToken(RefindConfigParser.CLOSE_BRACE, 0)\n\n        def sub_option(self, i:int=None):\n            if i is None:\n                return self.getTypedRuleContexts(RefindConfigParser.Sub_optionContext)\n            else:\n                return self.getTypedRuleContext(RefindConfigParser.Sub_optionContext,i)\n\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_sub_menu\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitSub_menu\" ):\n                return visitor.visitSub_menu(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def sub_menu(self):\n\n        localctx = RefindConfigParser.Sub_menuContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 28, self.RULE_sub_menu)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 102\n            self.menu_entry()\n            self.state = 103\n            self.match(RefindConfigParser.OPEN_BRACE)\n            self.state = 105 \n            self._errHandler.sync(self)\n            _la = self._input.LA(1)\n            while True:\n                self.state = 104\n                self.sub_option()\n                self.state = 107 \n                self._errHandler.sync(self)\n                _la = self._input.LA(1)\n                if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & 94976) != 0)):\n                    break\n\n            self.state = 109\n            self.match(RefindConfigParser.CLOSE_BRACE)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class Sub_optionContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def loader(self):\n            return self.getTypedRuleContext(RefindConfigParser.LoaderContext,0)\n\n\n        def sub_initrd(self):\n            return self.getTypedRuleContext(RefindConfigParser.Sub_initrdContext,0)\n\n\n        def graphics(self):\n            return self.getTypedRuleContext(RefindConfigParser.GraphicsContext,0)\n\n\n        def sub_boot_options(self):\n            return self.getTypedRuleContext(RefindConfigParser.Sub_boot_optionsContext,0)\n\n\n        def add_boot_options(self):\n            return self.getTypedRuleContext(RefindConfigParser.Add_boot_optionsContext,0)\n\n\n        def disabled(self):\n            return self.getTypedRuleContext(RefindConfigParser.DisabledContext,0)\n\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_sub_option\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitSub_option\" ):\n                return visitor.visitSub_option(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def sub_option(self):\n\n        localctx = RefindConfigParser.Sub_optionContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 30, self.RULE_sub_option)\n        try:\n            self.state = 117\n            self._errHandler.sync(self)\n            token = self._input.LA(1)\n            if token in [8]:\n                self.enterOuterAlt(localctx, 1)\n                self.state = 111\n                self.loader()\n                pass\n            elif token in [9]:\n                self.enterOuterAlt(localctx, 2)\n                self.state = 112\n                self.sub_initrd()\n                pass\n            elif token in [12]:\n                self.enterOuterAlt(localctx, 3)\n                self.state = 113\n                self.graphics()\n                pass\n            elif token in [13]:\n                self.enterOuterAlt(localctx, 4)\n                self.state = 114\n                self.sub_boot_options()\n                pass\n            elif token in [14]:\n                self.enterOuterAlt(localctx, 5)\n                self.state = 115\n                self.add_boot_options()\n                pass\n            elif token in [16]:\n                self.enterOuterAlt(localctx, 6)\n                self.state = 116\n                self.disabled()\n                pass\n            else:\n                raise NoViableAltException(self)\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class Sub_initrdContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def INITRD(self):\n            return self.getToken(RefindConfigParser.INITRD, 0)\n\n        def STRING(self):\n            return self.getToken(RefindConfigParser.STRING, 0)\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_sub_initrd\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitSub_initrd\" ):\n                return visitor.visitSub_initrd(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def sub_initrd(self):\n\n        localctx = RefindConfigParser.Sub_initrdContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 32, self.RULE_sub_initrd)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 119\n            self.match(RefindConfigParser.INITRD)\n            self.state = 121\n            self._errHandler.sync(self)\n            _la = self._input.LA(1)\n            if _la==21:\n                self.state = 120\n                self.match(RefindConfigParser.STRING)\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class Sub_boot_optionsContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def BOOT_OPTIONS(self):\n            return self.getToken(RefindConfigParser.BOOT_OPTIONS, 0)\n\n        def STRING(self):\n            return self.getToken(RefindConfigParser.STRING, 0)\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_sub_boot_options\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitSub_boot_options\" ):\n                return visitor.visitSub_boot_options(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def sub_boot_options(self):\n\n        localctx = RefindConfigParser.Sub_boot_optionsContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 34, self.RULE_sub_boot_options)\n        self._la = 0 # Token type\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 123\n            self.match(RefindConfigParser.BOOT_OPTIONS)\n            self.state = 125\n            self._errHandler.sync(self)\n            _la = self._input.LA(1)\n            if _la==21:\n                self.state = 124\n                self.match(RefindConfigParser.STRING)\n\n\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class Add_boot_optionsContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def ADD_BOOT_OPTIONS(self):\n            return self.getToken(RefindConfigParser.ADD_BOOT_OPTIONS, 0)\n\n        def STRING(self):\n            return self.getToken(RefindConfigParser.STRING, 0)\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_add_boot_options\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitAdd_boot_options\" ):\n                return visitor.visitAdd_boot_options(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def add_boot_options(self):\n\n        localctx = RefindConfigParser.Add_boot_optionsContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 36, self.RULE_add_boot_options)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 127\n            self.match(RefindConfigParser.ADD_BOOT_OPTIONS)\n            self.state = 128\n            self.match(RefindConfigParser.STRING)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n    class IncludeContext(ParserRuleContext):\n        __slots__ = 'parser'\n\n        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):\n            super().__init__(parent, invokingState)\n            self.parser = parser\n\n        def INCLUDE(self):\n            return self.getToken(RefindConfigParser.INCLUDE, 0)\n\n        def STRING(self):\n            return self.getToken(RefindConfigParser.STRING, 0)\n\n        def getRuleIndex(self):\n            return RefindConfigParser.RULE_include\n\n        def accept(self, visitor:ParseTreeVisitor):\n            if hasattr( visitor, \"visitInclude\" ):\n                return visitor.visitInclude(self)\n            else:\n                return visitor.visitChildren(self)\n\n\n\n\n    def include(self):\n\n        localctx = RefindConfigParser.IncludeContext(self, self._ctx, self.state)\n        self.enterRule(localctx, 38, self.RULE_include)\n        try:\n            self.enterOuterAlt(localctx, 1)\n            self.state = 130\n            self.match(RefindConfigParser.INCLUDE)\n            self.state = 131\n            self.match(RefindConfigParser.STRING)\n        except RecognitionException as re:\n            localctx.exception = re\n            self._errHandler.reportError(self, re)\n            self._errHandler.recover(self, re)\n        finally:\n            self.exitRule()\n        return localctx\n\n\n\n\n\n"
  },
  {
    "path": "src/refind_btrfs/boot/antlr4/RefindConfigParser.tokens",
    "content": "WHITESPACE=1\nNEWLINE=2\nEMPTY=3\nCOMMENT=4\nIGNORED_OPTION=5\nMENU_ENTRY=6\nVOLUME=7\nLOADER=8\nINITRD=9\nICON=10\nOS_TYPE=11\nGRAPHICS=12\nBOOT_OPTIONS=13\nADD_BOOT_OPTIONS=14\nFIRMWARE_BOOTNUM=15\nDISABLED=16\nINCLUDE=17\nOPEN_BRACE=18\nCLOSE_BRACE=19\nHEX_INTEGER=20\nSTRING=21\nOS_TYPE_PARAMETER=22\nGRAPHICS_PARAMETER=23\n'volume'=7\n'loader'=8\n'initrd'=9\n'icon'=10\n'options'=13\n'add_options'=14\n'firmware_bootnum'=15\n'disabled'=16\n'include'=17\n'{'=18\n'}'=19\n"
  },
  {
    "path": "src/refind_btrfs/boot/antlr4/RefindConfigParserVisitor.py",
    "content": "# Generated from c:/Users/Luka/Projects/Python/refind-btrfs/src/refind_btrfs/boot/antlr4/RefindConfigParser.g4 by ANTLR 4.13.1\nfrom antlr4 import *\nif \".\" in __name__:\n    from .RefindConfigParser import RefindConfigParser\nelse:\n    from RefindConfigParser import RefindConfigParser\n\n# This class defines a complete generic visitor for a parse tree produced by RefindConfigParser.\n\nclass RefindConfigParserVisitor(ParseTreeVisitor):\n\n    # Visit a parse tree produced by RefindConfigParser#refind.\n    def visitRefind(self, ctx:RefindConfigParser.RefindContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#config_option.\n    def visitConfig_option(self, ctx:RefindConfigParser.Config_optionContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#boot_stanza.\n    def visitBoot_stanza(self, ctx:RefindConfigParser.Boot_stanzaContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#menu_entry.\n    def visitMenu_entry(self, ctx:RefindConfigParser.Menu_entryContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#main_option.\n    def visitMain_option(self, ctx:RefindConfigParser.Main_optionContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#volume.\n    def visitVolume(self, ctx:RefindConfigParser.VolumeContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#loader.\n    def visitLoader(self, ctx:RefindConfigParser.LoaderContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#main_initrd.\n    def visitMain_initrd(self, ctx:RefindConfigParser.Main_initrdContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#icon.\n    def visitIcon(self, ctx:RefindConfigParser.IconContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#os_type.\n    def visitOs_type(self, ctx:RefindConfigParser.Os_typeContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#graphics.\n    def visitGraphics(self, ctx:RefindConfigParser.GraphicsContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#main_boot_options.\n    def visitMain_boot_options(self, ctx:RefindConfigParser.Main_boot_optionsContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#firmware_bootnum.\n    def visitFirmware_bootnum(self, ctx:RefindConfigParser.Firmware_bootnumContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#disabled.\n    def visitDisabled(self, ctx:RefindConfigParser.DisabledContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#sub_menu.\n    def visitSub_menu(self, ctx:RefindConfigParser.Sub_menuContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#sub_option.\n    def visitSub_option(self, ctx:RefindConfigParser.Sub_optionContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#sub_initrd.\n    def visitSub_initrd(self, ctx:RefindConfigParser.Sub_initrdContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#sub_boot_options.\n    def visitSub_boot_options(self, ctx:RefindConfigParser.Sub_boot_optionsContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#add_boot_options.\n    def visitAdd_boot_options(self, ctx:RefindConfigParser.Add_boot_optionsContext):\n        return self.visitChildren(ctx)\n\n\n    # Visit a parse tree produced by RefindConfigParser#include.\n    def visitInclude(self, ctx:RefindConfigParser.IncludeContext):\n        return self.visitChildren(ctx)\n\n\n\ndel RefindConfigParser"
  },
  {
    "path": "src/refind_btrfs/boot/antlr4/__init__.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom .RefindConfigLexer import RefindConfigLexer\nfrom .RefindConfigParser import RefindConfigParser\nfrom .RefindConfigParserVisitor import RefindConfigParserVisitor\n"
  },
  {
    "path": "src/refind_btrfs/boot/boot_options.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nfrom typing import Iterable, Optional, Self\n\nfrom more_itertools import last\n\nfrom refind_btrfs.common import constants\nfrom refind_btrfs.common.exceptions import RefindConfigError\nfrom refind_btrfs.device import BlockDevice, MountOptions, Subvolume\nfrom refind_btrfs.utility.helpers import (\n    has_items,\n    is_none_or_whitespace,\n    none_throws,\n    replace_root_part_in,\n    strip_quotes,\n)\n\n\nclass BootOptions:\n    def __init__(self, raw_options: Optional[str]) -> None:\n        root_location: Optional[tuple[int, str]] = None\n        root_mount_options: Optional[tuple[int, MountOptions]] = None\n        initrd_options: list[tuple[int, str]] = []\n        other_options: list[tuple[int, str]] = []\n\n        if not is_none_or_whitespace(raw_options):\n            split_options = strip_quotes(raw_options).split()\n\n            for position, option in enumerate(split_options):\n                if not is_none_or_whitespace(option):\n                    if option.startswith(constants.ROOT_PREFIX):\n                        normalized_option = option.removeprefix(constants.ROOT_PREFIX)\n\n                        if root_location is not None:\n                            root_option = constants.ROOT_PREFIX.rstrip(\n                                constants.PARAMETERIZED_OPTION_SEPARATOR\n                            )\n\n                            raise RefindConfigError(\n                                f\"The '{root_option}' boot option \"\n                                f\"cannot be defined multiple times!\"\n                            )\n\n                        root_location = (position, normalized_option)\n                    elif option.startswith(constants.ROOTFLAGS_PREFIX):\n                        normalized_option = option.removeprefix(\n                            constants.ROOTFLAGS_PREFIX\n                        )\n\n                        if root_mount_options is not None:\n                            rootflags_option = constants.ROOTFLAGS_PREFIX.rstrip(\n                                constants.PARAMETERIZED_OPTION_SEPARATOR\n                            )\n\n                            raise RefindConfigError(\n                                f\"The '{rootflags_option}' boot option \"\n                                f\"cannot be defined multiple times!\"\n                            )\n\n                        root_mount_options = (position, MountOptions(normalized_option))\n                    elif option.startswith(constants.INITRD_PREFIX):\n                        normalized_option = option.removeprefix(constants.INITRD_PREFIX)\n\n                        initrd_options.append((position, normalized_option))\n                    else:\n                        other_options.append((position, option))\n\n        self._root_location = root_location\n        self._root_mount_options = root_mount_options\n        self._initrd_options = initrd_options\n        self._other_options = other_options\n\n    def __str__(self) -> str:\n        root_location = self._root_location\n        root_mount_options = self._root_mount_options\n        initrd_options = self._initrd_options\n        other_options = self._other_options\n        result: list[str] = [constants.EMPTY_STR] * (\n            sum((len(initrd_options), len(other_options)))\n            + (1 if root_location is not None else 0)\n            + (1 if root_mount_options is not None else 0)\n        )\n\n        if root_location is not None:\n            result[root_location[0]] = constants.ROOT_PREFIX + root_location[1]\n\n        if root_mount_options is not None:\n            result[root_mount_options[0]] = constants.ROOTFLAGS_PREFIX + str(\n                root_mount_options[1]\n            )\n\n        if has_items(initrd_options):\n            for initrd_option in initrd_options:\n                result[initrd_option[0]] = constants.INITRD_PREFIX + initrd_option[1]\n\n        if has_items(other_options):\n            for other_option in other_options:\n                result[other_option[0]] = other_option[1]\n\n        if has_items(result):\n            joined_options = constants.BOOT_OPTION_SEPARATOR.join(result)\n\n            return constants.DOUBLE_QUOTE + joined_options + constants.DOUBLE_QUOTE\n\n        return constants.EMPTY_STR\n\n    def is_matched_with(self, block_device: BlockDevice) -> bool:\n        if block_device.has_root():\n            root_location = self.root_location\n\n            if root_location is not None:\n                root_partition = none_throws(block_device.root)\n                filesystem = none_throws(root_partition.filesystem)\n                normalized_root_location = last(\n                    strip_quotes(root_location).split(\n                        constants.PARAMETERIZED_OPTION_SEPARATOR\n                    )\n                )\n                root_location_comparers = [\n                    root_partition.label,\n                    root_partition.uuid,\n                    filesystem.label,\n                    filesystem.uuid,\n                ]\n\n                if (\n                    normalized_root_location in root_location_comparers\n                    or block_device.is_matched_with(normalized_root_location)\n                ):\n                    root_mount_options = self.root_mount_options\n                    subvolume = none_throws(filesystem.subvolume)\n\n                    return (\n                        root_mount_options.is_matched_with(subvolume)\n                        if root_mount_options is not None\n                        else False\n                    )\n\n        return False\n\n    def migrate_from_to(\n        self,\n        source_subvolume: Subvolume,\n        destination_subvolume: Subvolume,\n        include_paths: bool,\n    ) -> None:\n        root_mount_options = self.root_mount_options\n\n        if root_mount_options is not None:\n            root_mount_options.migrate_from_to(source_subvolume, destination_subvolume)\n\n        if include_paths:\n            initrd_options = self._initrd_options\n\n            if has_items(initrd_options):\n                source_logical_path = source_subvolume.logical_path\n                destination_logical_path = destination_subvolume.logical_path\n\n                self._initrd_options = [\n                    (\n                        initrd_option[0],\n                        replace_root_part_in(\n                            initrd_option[1],\n                            source_logical_path,\n                            destination_logical_path,\n                            (\n                                constants.FORWARD_SLASH,\n                                constants.BACKSLASH,\n                            ),\n                        ),\n                    )\n                    for initrd_option in initrd_options\n                ]\n\n    @classmethod\n    def merge(cls, all_boot_options: Iterable[BootOptions]) -> Self:\n        all_boot_options_str = [\n            strip_quotes(str(boot_options)) for boot_options in all_boot_options\n        ]\n\n        return cls(constants.SPACE.join(all_boot_options_str).strip())\n\n    @property\n    def root_location(self) -> Optional[str]:\n        root_location = self._root_location\n\n        if root_location is not None:\n            return root_location[1]\n\n        return None\n\n    @property\n    def root_mount_options(self) -> Optional[MountOptions]:\n        root_mount_options = self._root_mount_options\n\n        if root_mount_options is not None:\n            return root_mount_options[1]\n\n        return None\n\n    @property\n    def initrd_options(self) -> list[str]:\n        return [initrd_option[1] for initrd_option in self._initrd_options]\n\n    @property\n    def other_options(self) -> list[str]:\n        return [other_option[1] for other_option in self._other_options]\n"
  },
  {
    "path": "src/refind_btrfs/boot/boot_stanza.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nimport inspect\nimport re\nfrom collections import defaultdict\nfrom functools import cached_property, singledispatchmethod\nfrom itertools import chain\nfrom typing import Any, DefaultDict, Iterable, Iterator, Optional, Self, Set\nfrom pathlib import Path\n\nfrom more_itertools import always_iterable, last\n\nfrom refind_btrfs.common import BootFilesCheckResult, constants\nfrom refind_btrfs.common.enums import (\n    BootFilePathSource,\n    BootStanzaIconGenerationMode,\n    GraphicsParameter,\n    RefindOption,\n)\nfrom refind_btrfs.common.exceptions import RefindConfigError\nfrom refind_btrfs.device import BlockDevice, Subvolume\nfrom refind_btrfs.utility.helpers import (\n    has_items,\n    is_none_or_whitespace,\n    none_throws,\n    normalize_dir_separators_in,\n    replace_root_part_in,\n    strip_quotes,\n)\n\nfrom .boot_options import BootOptions\nfrom .sub_menu import SubMenu\n\n\nclass BootStanza:\n    def __init__(\n        self,\n        name: str,\n        volume: Optional[str],\n        loader_path: Optional[str],\n        initrd_path: Optional[str],\n        icon_path: Optional[str],\n        os_type: Optional[str],\n        graphics: Optional[bool],\n        boot_options: BootOptions,\n        firmware_bootnum: Optional[int],\n        is_disabled: bool,\n    ) -> None:\n        self._name = name\n        self._volume = volume\n        self._loader_path = loader_path\n        self._initrd_path = initrd_path\n        self._icon_path = icon_path\n        self._os_type = os_type\n        self._graphics = graphics\n        self._boot_options = boot_options\n        self._firmware_bootnum = firmware_bootnum\n        self._is_disabled = is_disabled\n        self._boot_files_check_result: Optional[BootFilesCheckResult] = None\n        self._sub_menus: Optional[list[SubMenu]] = None\n\n    def __eq__(self, other: object) -> bool:\n        if self is other:\n            return True\n\n        if isinstance(other, BootStanza):\n            self_boot_options = self.boot_options\n            other_boot_options = other.boot_options\n\n            return (\n                self.volume == other.volume\n                and self.loader_path == other.loader_path\n                and str(self_boot_options) == str(other_boot_options)\n            )\n\n        return False\n\n    def __hash__(self):\n        boot_options = self.boot_options\n\n        return hash((self.volume, self.loader_path, str(boot_options)))\n\n    def __str__(self) -> str:\n        result: list[str] = []\n        main_indent = constants.EMPTY_STR\n        option_indent = constants.TAB\n\n        name = self.name\n        result.append(f\"{main_indent}{RefindOption.MENU_ENTRY.value} {name} {{\")\n\n        icon_path = self.icon_path\n\n        if not is_none_or_whitespace(icon_path):\n            result.append(f\"{option_indent}{RefindOption.ICON.value} {icon_path}\")\n\n        volume = self.volume\n\n        if not is_none_or_whitespace(volume):\n            result.append(f\"{option_indent}{RefindOption.VOLUME.value} {volume}\")\n\n        loader_path = self.loader_path\n\n        if not is_none_or_whitespace(loader_path):\n            result.append(f\"{option_indent}{RefindOption.LOADER.value} {loader_path}\")\n\n        initrd_path = self.initrd_path\n\n        if not is_none_or_whitespace(initrd_path):\n            result.append(f\"{option_indent}{RefindOption.INITRD.value} {initrd_path}\")\n\n        os_type = self.os_type\n\n        if not is_none_or_whitespace(os_type):\n            result.append(f\"{option_indent}{RefindOption.OS_TYPE.value} {os_type}\")\n\n        graphics = self.graphics\n\n        if graphics is not None:\n            graphics_parameter = (\n                GraphicsParameter.ON if graphics else GraphicsParameter.OFF\n            )\n            result.append(\n                f\"{option_indent}{RefindOption.GRAPHICS.value} {graphics_parameter.value}\"\n            )\n\n        boot_options_str = str(self.boot_options)\n\n        if not is_none_or_whitespace(boot_options_str):\n            result.append(\n                f\"{option_indent}{RefindOption.BOOT_OPTIONS.value} {boot_options_str}\"\n            )\n\n        firmware_bootnum = self.firmware_bootnum\n\n        if firmware_bootnum is not None:\n            result.append(\n                f\"{option_indent}{RefindOption.FIRMWARE_BOOTNUM.value} {firmware_bootnum:04x}\"\n            )\n\n        sub_menus = self.sub_menus\n\n        if has_items(sub_menus):\n            result.extend(str(sub_menu) for sub_menu in none_throws(sub_menus))\n\n        is_disabled = self.is_disabled\n\n        if is_disabled:\n            result.append(f\"{option_indent}{RefindOption.DISABLED.value}\")\n\n        result.append(f\"{main_indent}}}\")\n\n        return constants.NEWLINE.join(result)\n\n    def with_boot_files_check_result(\n        self, subvolume: Subvolume, include_sub_menus: bool\n    ) -> Self:\n        normalized_name = self.normalized_name\n        all_boot_file_paths = self.all_boot_file_paths\n        logical_path = subvolume.logical_path\n        matched_boot_files: list[str] = []\n        unmatched_boot_files: list[str] = []\n        sources = [BootFilePathSource.BOOT_STANZA]\n\n        if include_sub_menus:\n            sources.append(BootFilePathSource.SUB_MENU)\n\n        for source in sources:\n            boot_file_paths = always_iterable(all_boot_file_paths.get(source))\n\n            for boot_file_path in boot_file_paths:\n                # Handle both paths with subvolume prefix (/@/boot/...) and without (/boot/...)\n                replaced_path_str = replace_root_part_in(\n                    boot_file_path, logical_path, str(subvolume.filesystem_path)\n                )\n\n                if replaced_path_str == boot_file_path:\n                    replaced_file_path = subvolume.filesystem_path / Path(boot_file_path).relative_to('/')\n                else:\n                    replaced_file_path = Path(replaced_path_str)\n\n                if replaced_file_path.exists():\n                    matched_boot_files.append(boot_file_path)\n                else:\n                    unmatched_boot_files.append(boot_file_path)\n\n        self._boot_files_check_result = BootFilesCheckResult(\n            normalized_name, logical_path, matched_boot_files, unmatched_boot_files\n        )\n\n        return self\n\n    def with_sub_menus(self, sub_menus: Iterable[SubMenu]) -> Self:\n        self._sub_menus = list(sub_menus)\n\n        return self\n\n    @singledispatchmethod\n    def is_matched_with(self, argument: Any) -> bool:\n        frame = none_throws(inspect.currentframe())\n\n        raise NotImplementedError(\n            f\"Cannot call the '{inspect.getframeinfo(frame).function}' method \"\n            f\"for parameter of type '{type(argument).__name__}'!\"\n        )\n\n    def has_unmatched_boot_files(self) -> bool:\n        boot_files_check_result = self.boot_files_check_result\n\n        if boot_files_check_result is not None:\n            return boot_files_check_result.has_unmatched_boot_files()\n\n        return False\n\n    def has_sub_menus(self) -> bool:\n        return has_items(self.sub_menus)\n\n    def can_be_used_for_bootable_snapshot(self) -> bool:\n        volume = self.volume\n        loader_path = self.loader_path\n        initrd_path = self.initrd_path\n        is_disabled = self.is_disabled\n\n        return (\n            not is_none_or_whitespace(volume)\n            and not is_none_or_whitespace(loader_path)\n            and not is_none_or_whitespace(initrd_path)\n            and not is_disabled\n        )\n\n    def validate_boot_files_check_result(self) -> None:\n        if self.has_unmatched_boot_files():\n            boot_files_check_result = none_throws(self.boot_files_check_result)\n            boot_stanza_name = boot_files_check_result.required_by_boot_stanza_name\n            logical_path = boot_files_check_result.expected_logical_path\n            unmatched_boot_files = boot_files_check_result.unmatched_boot_files\n\n            raise RefindConfigError(\n                f\"Detected boot files required by the '{boot_stanza_name}' boot \"\n                f\"stanza which are not matched with the '{logical_path}' subvolume: \"\n                f\"{constants.DEFAULT_ITEMS_SEPARATOR.join(unmatched_boot_files)}!\"\n            )\n\n    def validate_icon_path(\n        self, icon_generation_mode: BootStanzaIconGenerationMode\n    ) -> None:\n        if icon_generation_mode != BootStanzaIconGenerationMode.DEFAULT:\n            normalized_name = self.normalized_name\n            icon_path = self.icon_path\n\n            if is_none_or_whitespace(icon_path):\n                raise RefindConfigError(\n                    f\"The '{normalized_name}' boot stanza is missing the \"\n                    f\"'{RefindOption.ICON.value}' option which must be defined in case \"\n                    f\"'{icon_generation_mode.value}' is the selected mode of boot stanza \"\n                    \"icon generation!\"\n                )\n\n    @is_matched_with.register(BlockDevice)\n    def _is_matched_with_block_device(self, block_device: BlockDevice) -> bool:\n        if self.can_be_used_for_bootable_snapshot():\n            boot_options = self.boot_options\n\n            if boot_options.is_matched_with(block_device):\n                return True\n            else:\n                sub_menus = self.sub_menus\n\n                if has_items(sub_menus):\n                    return any(\n                        sub_menu.is_matched_with(block_device)\n                        for sub_menu in none_throws(sub_menus)\n                    )\n\n        return False\n\n    @is_matched_with.register(str)\n    def _is_matched_with_loader_filename(self, loader_filename: str) -> bool:\n        return self._loader_filename == loader_filename\n\n    def _get_all_boot_file_paths(\n        self,\n    ) -> Iterator[tuple[BootFilePathSource, str]]:\n        source = BootFilePathSource.BOOT_STANZA\n        is_disabled = self.is_disabled\n\n        if not is_disabled:\n            loader_path = self.loader_path\n            initrd_path = self.initrd_path\n            boot_options = self.boot_options\n\n            if not is_none_or_whitespace(loader_path):\n                yield (source, none_throws(loader_path))\n\n            if not is_none_or_whitespace(initrd_path):\n                yield (source, none_throws(initrd_path))\n\n            yield from (\n                (source, initrd_option) for initrd_option in boot_options.initrd_options\n            )\n\n            sub_menus = self.sub_menus\n\n            if has_items(sub_menus):\n                yield from chain.from_iterable(\n                    sub_menu.all_boot_file_paths for sub_menu in none_throws(sub_menus)\n                )\n\n    @property\n    def name(self) -> str:\n        return self._name\n\n    @property\n    def normalized_name(self) -> str:\n        return strip_quotes(self.name)\n\n    @property\n    def volume(self) -> Optional[str]:\n        return self._volume\n\n    @property\n    def normalized_volume(self) -> Optional[str]:\n        volume = self.volume\n\n        if not is_none_or_whitespace(volume):\n            whitespace_pattern = re.compile(constants.WHITESPACE_PATTERN)\n            stripped_volume = strip_quotes(volume)\n\n            return whitespace_pattern.sub(\"_\", stripped_volume)\n\n        return None\n\n    @property\n    def loader_path(self) -> Optional[str]:\n        return self._loader_path\n\n    @property\n    def initrd_path(self) -> Optional[str]:\n        return self._initrd_path\n\n    @property\n    def icon_path(self) -> Optional[str]:\n        return self._icon_path\n\n    @property\n    def os_type(self) -> Optional[str]:\n        return self._os_type\n\n    @property\n    def graphics(self) -> Optional[bool]:\n        return self._graphics\n\n    @property\n    def boot_options(self) -> BootOptions:\n        return self._boot_options\n\n    @property\n    def firmware_bootnum(self) -> Optional[int]:\n        return self._firmware_bootnum\n\n    @property\n    def is_disabled(self) -> bool:\n        return self._is_disabled\n\n    @property\n    def boot_files_check_result(self) -> Optional[BootFilesCheckResult]:\n        return self._boot_files_check_result\n\n    @property\n    def sub_menus(self) -> Optional[list[SubMenu]]:\n        return self._sub_menus\n\n    @cached_property\n    def filename(self) -> str:\n        if self.can_be_used_for_bootable_snapshot():\n            normalized_volume = self.normalized_volume\n            loader_filename = self._loader_filename\n            extension = constants.CONFIG_FILE_EXTENSION\n\n            return f\"{normalized_volume}_{loader_filename}{extension}\".lower()\n\n        return constants.EMPTY_STR\n\n    @cached_property\n    def all_boot_file_paths(self) -> DefaultDict[BootFilePathSource, Set[str]]:\n        result = defaultdict(set)\n        all_boot_file_paths = self._get_all_boot_file_paths()\n\n        for boot_file_path_tuple in all_boot_file_paths:\n            key = boot_file_path_tuple[0]\n            value = normalize_dir_separators_in(boot_file_path_tuple[1])\n\n            result[key].add(value)\n\n        return result\n\n    @cached_property\n    def _loader_filename(self) -> str:\n        loader_path = self.loader_path\n\n        if not is_none_or_whitespace(loader_path):\n            dir_separator_pattern = re.compile(constants.DIR_SEPARATOR_PATTERN)\n            split_loader_path = dir_separator_pattern.split(\n                none_throws(self.loader_path)\n            )\n\n            return last(split_loader_path)\n\n        return constants.EMPTY_STR\n"
  },
  {
    "path": "src/refind_btrfs/boot/file_refind_config_provider.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport re\nfrom pathlib import Path\nfrom typing import Iterable, Iterator\n\nfrom antlr4 import CommonTokenStream, FileStream\nfrom injector import inject\nfrom more_itertools import last, one\n\nfrom refind_btrfs.common import constants\nfrom refind_btrfs.common.abc.factories import BaseLoggerFactory\nfrom refind_btrfs.common.abc.providers import (\n    BasePackageConfigProvider,\n    BasePersistenceProvider,\n    BaseRefindConfigProvider,\n)\nfrom refind_btrfs.common.enums import ConfigInitializationType, RefindOption\nfrom refind_btrfs.common.exceptions import RefindConfigError, RefindSyntaxError\nfrom refind_btrfs.device import Partition\nfrom refind_btrfs.utility.helpers import (\n    checked_cast,\n    has_items,\n    is_none_or_whitespace,\n    is_singleton,\n    item_count_suffix,\n    none_throws,\n)\n\nfrom .antlr4 import RefindConfigLexer, RefindConfigParser\nfrom .boot_stanza import BootStanza\nfrom .refind_config import RefindConfig\nfrom .refind_listeners import RefindErrorListener\nfrom .refind_visitors import BootStanzaVisitor, IncludeVisitor\n\n\nclass FileRefindConfigProvider(BaseRefindConfigProvider):\n    all_config_file_paths: dict[Partition, Path] = {}\n\n    @inject\n    def __init__(\n        self,\n        logger_factory: BaseLoggerFactory,\n        package_config_provider: BasePackageConfigProvider,\n        persistence_provider: BasePersistenceProvider,\n    ) -> None:\n        self._logger = logger_factory.logger(__name__)\n        self._package_config_provider = package_config_provider\n        self._persistence_provider = persistence_provider\n        self._refind_configs: dict[Path, RefindConfig] = {}\n\n    def get_config(self, partition: Partition) -> RefindConfig:\n        logger = self._logger\n        config_file_path = FileRefindConfigProvider.all_config_file_paths.get(partition)\n        should_begin_search = config_file_path is None or not config_file_path.exists()\n\n        if should_begin_search:\n            package_config_provider = self._package_config_provider\n            package_config = package_config_provider.get_config()\n            boot_stanza_generation = package_config.boot_stanza_generation\n            refind_config_file = boot_stanza_generation.refind_config\n\n            logger.info(\n                f\"Searching for the '{refind_config_file}' file on '{partition.name}'.\"\n            )\n\n            refind_config_search_result = partition.search_paths_for(refind_config_file)\n\n            if not has_items(refind_config_search_result):\n                raise RefindConfigError(\n                    f\"Could not find the '{refind_config_file}' file!\"\n                )\n\n            if not is_singleton(refind_config_search_result):\n                raise RefindConfigError(\n                    f\"Found multiple '{refind_config_file}' files (at most one is expected)!\"\n                )\n\n            config_file_path = one(none_throws(refind_config_search_result)).resolve()\n\n            FileRefindConfigProvider.all_config_file_paths[partition] = config_file_path\n\n        return self._read_config_from(none_throws(config_file_path))\n\n    def save_config(self, config: RefindConfig) -> None:\n        logger = self._logger\n        persistence_provider = self._persistence_provider\n        boot_stanzas = config.boot_stanzas\n\n        if has_items(boot_stanzas):\n            config_file_path = config.file_path\n            destination_directory = config_file_path.parent\n            refind_directory = destination_directory.parent\n\n            if not destination_directory.exists():\n                logger.info(\n                    \"Creating the \"\n                    f\"'{destination_directory.relative_to(refind_directory)}' \"\n                    \"destination directory.\"\n                )\n\n                destination_directory.mkdir()\n\n            try:\n                logger.info(\n                    f\"Writing to the '{config_file_path.relative_to(refind_directory)}' file.\"\n                )\n\n                with config_file_path.open(\"w\") as config_file:\n                    lines_for_writing: list[str] = []\n\n                    lines_for_writing.append(\n                        constants.NEWLINE.join(\n                            str(boot_stanza)\n                            for boot_stanza in none_throws(boot_stanzas)\n                        )\n                    )\n                    lines_for_writing.append(constants.NEWLINE)\n                    config_file.writelines(lines_for_writing)\n            except OSError as e:\n                logger.exception(\"Path.open('w') call failed!\")\n                raise RefindConfigError(\n                    f\"Could not write to the '{config_file_path.name}' file!\"\n                ) from e\n\n            config.refresh_file_stat()\n            persistence_provider.save_refind_config(config)\n\n    def append_to_config(self, config: RefindConfig) -> None:\n        logger = self._logger\n        persistence_provider = self._persistence_provider\n        config_file_path = config.file_path\n        actual_config = persistence_provider.get_refind_config(config_file_path)\n\n        if actual_config is not None:\n            new_included_configs = config.get_included_configs_difference_from(\n                actual_config\n            )\n\n            if has_items(new_included_configs):\n                included_configs_for_appending = none_throws(new_included_configs)\n\n                try:\n                    with config_file_path.open(\"r\") as config_file:\n                        all_lines = config_file.readlines()\n                        last_line = last(all_lines)\n                except OSError as e:\n                    logger.exception(\"Path.open('r') call failed!\")\n                    raise RefindConfigError(\n                        f\"Could not read from the '{config_file_path}' file!\"\n                    ) from e\n                else:\n                    include_option = RefindOption.INCLUDE.value\n                    suffix = item_count_suffix(included_configs_for_appending)\n\n                    try:\n                        logger.info(\n                            f\"Appending {len(included_configs_for_appending)} '{include_option}' \"\n                            f\"directive{suffix} to the '{config_file_path.name}' file.\"\n                        )\n\n                        with config_file_path.open(\"a\") as config_file:\n                            lines_for_appending: list[str] = []\n                            should_prepend_newline = False\n\n                            if not is_none_or_whitespace(last_line):\n                                include_option_pattern = re.compile(\n                                    constants.INCLUDE_OPTION_PATTERN, re.DOTALL\n                                )\n\n                                should_prepend_newline = (\n                                    not include_option_pattern.match(last_line)\n                                )\n\n                            if should_prepend_newline:\n                                lines_for_appending.append(constants.NEWLINE)\n\n                            destination_directory = config_file_path.parent\n\n                            for included_config in included_configs_for_appending:\n                                included_config_relative_file_path = (\n                                    included_config.file_path.relative_to(\n                                        destination_directory\n                                    )\n                                )\n\n                                lines_for_appending.append(\n                                    f\"{include_option} {included_config_relative_file_path}\"\n                                    f\"{constants.NEWLINE}\"\n                                )\n\n                            config_file.writelines(lines_for_appending)\n                    except OSError as e:\n                        logger.exception(\"Path.open('a') call failed!\")\n                        raise RefindConfigError(\n                            f\"Could not append to the '{config_file_path.name}' file!\"\n                        ) from e\n\n                config.refresh_file_stat()\n\n            persistence_provider.save_refind_config(config)\n\n    def _read_config_from(self, config_file_path: Path) -> RefindConfig:\n        persistence_provider = self._persistence_provider\n        persisted_refind_config = persistence_provider.get_refind_config(\n            config_file_path\n        )\n        current_refind_config = self._refind_configs.get(config_file_path)\n\n        if persisted_refind_config is None:\n            logger = self._logger\n\n            logger.info(f\"Analyzing the '{config_file_path.name}' file.\")\n\n            try:\n                input_stream = FileStream(str(config_file_path), encoding=\"utf-8\")\n                lexer = RefindConfigLexer(input_stream)\n                token_stream = CommonTokenStream(lexer)\n                parser = RefindConfigParser(token_stream)\n                error_listener = RefindErrorListener()\n\n                parser.removeErrorListeners()\n                parser.addErrorListener(error_listener)\n\n                refind_context = parser.refind()\n            except RefindSyntaxError as e:\n                logger.exception(\n                    f\"Error while parsing the '{config_file_path.name}' file!\"\n                )\n                raise RefindConfigError(\n                    \"Could not load rEFInd configuration from file!\"\n                ) from e\n            else:\n                config_option_contexts = checked_cast(\n                    list[RefindConfigParser.Config_optionContext],\n                    refind_context.config_option(),\n                )\n                boot_stanzas = FileRefindConfigProvider._map_to_boot_stanzas(\n                    config_option_contexts\n                )\n                includes = FileRefindConfigProvider._map_to_includes(\n                    config_option_contexts\n                )\n                included_configs = self._read_included_configs_from(\n                    config_file_path.parent, includes\n                )\n\n                current_refind_config = (\n                    RefindConfig(config_file_path)\n                    .with_boot_stanzas(boot_stanzas)\n                    .with_included_configs(included_configs)\n                    .with_initialization_type(ConfigInitializationType.PARSED)\n                )\n\n                persistence_provider.save_refind_config(current_refind_config)\n        elif current_refind_config is None:\n            current_refind_config = persisted_refind_config.with_initialization_type(\n                ConfigInitializationType.PERSISTED\n            )\n\n            if current_refind_config.has_included_configs():\n                current_included_configs = none_throws(\n                    current_refind_config.included_configs\n                )\n                actual_included_configs = [\n                    self._read_config_from(included_config.file_path)\n                    for included_config in current_included_configs\n                    if included_config.file_path.exists()\n                ]\n                current_refind_config = current_refind_config.with_included_configs(\n                    actual_included_configs\n                )\n\n        self._refind_configs[config_file_path] = current_refind_config\n\n        return current_refind_config\n\n    def _read_included_configs_from(\n        self, root_directory: Path, includes: Iterable[str]\n    ) -> Iterator[RefindConfig]:\n        logger = self._logger\n\n        for include in includes:\n            included_config_file_path = root_directory / include\n\n            if included_config_file_path.exists():\n                yield self._read_config_from(included_config_file_path.resolve())\n            else:\n                logger.warning(\n                    f\"The included config file '{included_config_file_path.name}' does not exist.\"\n                )\n\n    @staticmethod\n    def _map_to_boot_stanzas(\n        config_option_contexts: list[RefindConfigParser.Config_optionContext],\n    ) -> Iterator[BootStanza]:\n        if has_items(config_option_contexts):\n            boot_stanza_visitor = BootStanzaVisitor()\n\n            for config_option_context in config_option_contexts:\n                boot_stanza_context = config_option_context.boot_stanza()\n\n                if boot_stanza_context is not None:\n                    yield checked_cast(\n                        BootStanza, boot_stanza_context.accept(boot_stanza_visitor)\n                    )\n\n    @staticmethod\n    def _map_to_includes(\n        config_option_contexts: list[RefindConfigParser.Config_optionContext],\n    ) -> Iterator[str]:\n        if has_items(config_option_contexts):\n            include_visitor = IncludeVisitor()\n\n            for config_option_context in config_option_contexts:\n                include_context = config_option_context.include()\n\n                if include_context is not None:\n                    yield checked_cast(str, include_context.accept(include_visitor))\n"
  },
  {
    "path": "src/refind_btrfs/boot/migrations/__init__.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom .migration import Migration\n"
  },
  {
    "path": "src/refind_btrfs/boot/migrations/icon_migration_strategies.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\n\nfrom refind_btrfs.common import BtrfsLogo, Icon\nfrom refind_btrfs.common.abc.commands import IconCommand\nfrom refind_btrfs.common.enums import BootStanzaIconGenerationMode\n\n\nclass BaseIconMigrationStrategy(ABC):\n    def __init__(\n        self, icon_command: IconCommand, refind_config_path: Path, source_icon: str\n    ) -> None:\n        self._icon_command = icon_command\n        self._refind_config_path = refind_config_path\n        self._source_icon_path = Path(source_icon)\n\n    @abstractmethod\n    def migrate(self) -> str:\n        pass\n\n\nclass DefaultMigrationStrategy(BaseIconMigrationStrategy):\n    def migrate(self) -> str:\n        return str(self._source_icon_path)\n\n\nclass CustomMigrationStrategy(BaseIconMigrationStrategy):\n    def __init__(\n        self,\n        icon_command: IconCommand,\n        refind_config_path: Path,\n        source_icon: str,\n        custom_icon_path: Path,\n    ) -> None:\n        super().__init__(icon_command, refind_config_path, source_icon)\n\n        self._custom_icon_path = custom_icon_path\n\n    def migrate(self) -> str:\n        icon_command = self._icon_command\n        refind_config_path = self._refind_config_path\n        source_icon_path = self._source_icon_path\n        custom_icon_path = self._custom_icon_path\n        destination_icon_relative_path = icon_command.validate_custom_icon(\n            refind_config_path, source_icon_path, custom_icon_path\n        )\n\n        return str(destination_icon_relative_path)\n\n\nclass EmbedBtrfsLogoStrategy(BaseIconMigrationStrategy):\n    def __init__(\n        self,\n        icon_command: IconCommand,\n        refind_config_path: Path,\n        source_icon: str,\n        btrfs_logo: BtrfsLogo,\n    ) -> None:\n        super().__init__(icon_command, refind_config_path, source_icon)\n\n        self._btrfs_logo = btrfs_logo\n\n    def migrate(self) -> str:\n        icon_command = self._icon_command\n        refind_config_path = self._refind_config_path\n        source_icon_path = self._source_icon_path\n        btrfs_logo = self._btrfs_logo\n        destination_icon_relative_path = icon_command.embed_btrfs_logo_into_source_icon(\n            refind_config_path, source_icon_path, btrfs_logo\n        )\n\n        return str(destination_icon_relative_path)\n\n\nclass IconMigrationFactory:\n    @staticmethod\n    def migration_strategy(\n        icon_command: IconCommand,\n        refind_config_path: Path,\n        source_icon: str,\n        icon: Icon,\n    ) -> BaseIconMigrationStrategy:\n        mode = icon.mode\n\n        if mode == BootStanzaIconGenerationMode.DEFAULT:\n            return DefaultMigrationStrategy(\n                icon_command, refind_config_path, source_icon\n            )\n\n        if mode == BootStanzaIconGenerationMode.CUSTOM:\n            custom_icon_path = icon.path\n\n            return CustomMigrationStrategy(\n                icon_command, refind_config_path, source_icon, custom_icon_path\n            )\n\n        if mode == BootStanzaIconGenerationMode.EMBED_BTRFS_LOGO:\n            btrfs_logo = icon.btrfs_logo\n\n            return EmbedBtrfsLogoStrategy(\n                icon_command, refind_config_path, source_icon, btrfs_logo\n            )\n\n        raise ValueError(\n            \"The 'icon' parameter's 'mode' property contains an unexpected value!\"\n        )\n"
  },
  {
    "path": "src/refind_btrfs/boot/migrations/main_migration_strategies.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport re\nfrom abc import ABC, abstractmethod\nfrom copy import deepcopy\nfrom functools import singledispatchmethod\nfrom pathlib import Path\nfrom typing import Any, Optional\n\nfrom refind_btrfs.common import BootStanzaGeneration, Icon, constants\nfrom refind_btrfs.common.abc.commands import IconCommand\nfrom refind_btrfs.device import Subvolume\nfrom refind_btrfs.utility.helpers import (\n    default_if_none,\n    is_none_or_whitespace,\n    none_throws,\n    replace_root_part_in,\n)\n\nfrom ..boot_options import BootOptions\nfrom ..boot_stanza import BootStanza\nfrom ..sub_menu import SubMenu\nfrom .icon_migration_strategies import IconMigrationFactory\nfrom .state import State\n\n\nclass BaseMainMigrationStrategy(ABC):\n    def __init__(\n        self,\n        is_latest: bool,\n        refind_config_path: Path,\n        current_state: State,\n        source_subvolume: Subvolume,\n        destination_subvolume: Subvolume,\n        boot_stanza_generation: BootStanzaGeneration,\n    ) -> None:\n        self._is_latest = is_latest\n        self._refind_config_path = refind_config_path\n        self._current_state = current_state\n        self._source_subvolume = source_subvolume\n        self._destination_subvolume = destination_subvolume\n        self._boot_stanza_generation = boot_stanza_generation\n\n    @abstractmethod\n    def migrate(self) -> State:\n        pass\n\n    @property\n    def destination_name(self) -> str:\n        destination_subvolume = self._destination_subvolume\n\n        if not destination_subvolume.is_named():\n            raise ValueError(\"The 'destination_subvolume' instance must be named!\")\n\n        current_name = self._current_state.name\n        destination_subvolume_name = none_throws(destination_subvolume.name)\n        subvolume_name_pattern = re.compile(rf\"\\({constants.SUBVOLUME_NAME_PATTERN}\\)\")\n        match = subvolume_name_pattern.search(current_name)\n\n        if match:\n            destination_name = subvolume_name_pattern.sub(\n                f\"({destination_subvolume_name})\", current_name\n            )\n        else:\n            destination_name = f\"{current_name} ({destination_subvolume_name})\"\n\n        return f\"{constants.DOUBLE_QUOTE}{destination_name}{constants.DOUBLE_QUOTE}\"\n\n    @property\n    def destination_loader_path(self) -> Optional[str]:\n        current_loader_path = self._current_state.loader_path\n\n        if not is_none_or_whitespace(current_loader_path):\n            return replace_root_part_in(\n                none_throws(current_loader_path),\n                self._source_subvolume.logical_path,\n                self._destination_subvolume.logical_path,\n            )\n\n        return None\n\n    @property\n    def destination_initrd_path(self) -> Optional[str]:\n        current_initrd_path = self._current_state.initrd_path\n\n        if not is_none_or_whitespace(current_initrd_path):\n            return replace_root_part_in(\n                none_throws(current_initrd_path),\n                self._source_subvolume.logical_path,\n                self._destination_subvolume.logical_path,\n            )\n\n        return None\n\n    @property\n    def destination_boot_options(self) -> Optional[BootOptions]:\n        current_boot_options = self._current_state.boot_options\n\n        if current_boot_options is not None:\n            destination_boot_options = deepcopy(current_boot_options)\n            include_paths = self.include_paths\n\n            destination_boot_options.migrate_from_to(\n                self._source_subvolume,\n                self._destination_subvolume,\n                include_paths,\n            )\n\n            return destination_boot_options\n\n        return None\n\n    @property\n    def destination_add_boot_options(self) -> Optional[BootOptions]:\n        current_add_boot_options = self._current_state.add_boot_options\n\n        if current_add_boot_options is not None:\n            destination_add_boot_options = deepcopy(current_add_boot_options)\n            include_paths = self.include_paths\n\n            destination_add_boot_options.migrate_from_to(\n                self._source_subvolume,\n                self._destination_subvolume,\n                include_paths,\n            )\n\n            return destination_add_boot_options\n\n        return None\n\n    @property\n    def include_paths(self) -> bool:\n        return self._boot_stanza_generation.include_paths\n\n    @property\n    def icon(self) -> Icon:\n        return self._boot_stanza_generation.icon\n\n\nclass BootStanzaMigrationStrategy(BaseMainMigrationStrategy):\n    def __init__(\n        self,\n        is_latest: bool,\n        refind_config_path: Path,\n        boot_stanza: BootStanza,\n        source_subvolume: Subvolume,\n        destination_subvolume: Subvolume,\n        boot_stanza_generation: BootStanzaGeneration,\n        icon_command: IconCommand,\n    ) -> None:\n        super().__init__(\n            is_latest,\n            refind_config_path,\n            State(\n                boot_stanza.normalized_name,\n                boot_stanza.loader_path,\n                boot_stanza.initrd_path,\n                boot_stanza.icon_path,\n                boot_stanza.boot_options,\n                None,\n            ),\n            source_subvolume,\n            destination_subvolume,\n            boot_stanza_generation,\n        )\n\n        self._icon_command = icon_command\n\n    def migrate(self) -> State:\n        include_paths = self.include_paths\n        is_latest = self._is_latest\n        current_state = self._current_state\n        destination_loader_path = constants.EMPTY_STR\n        destination_initrd_path = constants.EMPTY_STR\n\n        if is_latest:\n            destination_loader_path = none_throws(current_state.loader_path)\n            destination_initrd_path = none_throws(current_state.initrd_path)\n\n        if include_paths:\n            destination_loader_path = none_throws(self.destination_loader_path)\n            destination_initrd_path_candidate = self.destination_initrd_path\n\n            if not is_none_or_whitespace(destination_initrd_path_candidate):\n                destination_initrd_path = none_throws(destination_initrd_path_candidate)\n\n        icon_migration_strategy = IconMigrationFactory.migration_strategy(\n            self._icon_command,\n            self._refind_config_path,\n            default_if_none(current_state.icon_path, constants.EMPTY_STR),\n            self.icon,\n        )\n\n        destination_icon_path = icon_migration_strategy.migrate()\n\n        return State(\n            self.destination_name,\n            destination_loader_path,\n            destination_initrd_path,\n            destination_icon_path,\n            self.destination_boot_options,\n            None,\n        )\n\n\nclass SubMenuMigrationStrategy(BaseMainMigrationStrategy):\n    def __init__(\n        self,\n        is_latest: bool,\n        refind_config_path: Path,\n        sub_menu: SubMenu,\n        source_subvolume: Subvolume,\n        destination_subvolume: Subvolume,\n        boot_stanza_generation: BootStanzaGeneration,\n        inherit_from_state: State,\n    ) -> None:\n        super().__init__(\n            is_latest,\n            refind_config_path,\n            State(\n                sub_menu.normalized_name,\n                sub_menu.loader_path,\n                sub_menu.initrd_path,\n                None,\n                sub_menu.boot_options,\n                sub_menu.add_boot_options,\n            ),\n            source_subvolume,\n            destination_subvolume,\n            boot_stanza_generation,\n        )\n\n        self._inherit_from_state = inherit_from_state\n\n    def migrate(self) -> State:\n        include_paths = self.include_paths\n        is_latest = self._is_latest\n        current_state = self._current_state\n        inherit_from_state = self._inherit_from_state\n        destination_loader_path = current_state.loader_path\n        destination_initrd_path = current_state.initrd_path\n        destination_boot_options: Optional[BootOptions] = None\n        destination_add_boot_options = self.destination_add_boot_options\n\n        if not is_latest:\n            if include_paths:\n                destination_loader_path = inherit_from_state.loader_path\n                destination_initrd_path = inherit_from_state.initrd_path\n\n            destination_boot_options = BootOptions.merge(\n                (\n                    none_throws(inherit_from_state.boot_options),\n                    none_throws(destination_add_boot_options),\n                )\n            )\n            destination_add_boot_options = BootOptions(constants.EMPTY_STR)\n\n        if include_paths:\n            destination_loader_path_candidate = self.destination_loader_path\n            destination_initrd_path_candidate = self.destination_initrd_path\n\n            if not is_none_or_whitespace(destination_loader_path_candidate):\n                destination_loader_path = destination_loader_path_candidate\n\n            if not is_none_or_whitespace(destination_initrd_path_candidate):\n                destination_initrd_path = destination_initrd_path_candidate\n\n        return State(\n            self.destination_name,\n            destination_loader_path,\n            destination_initrd_path,\n            None,\n            destination_boot_options,\n            destination_add_boot_options,\n        )\n\n\nclass MainMigrationFactory:\n    # pylint: disable=unused-argument\n    @singledispatchmethod\n    @staticmethod\n    def migration_strategy(\n        argument: Any,\n        is_latest: bool,\n        refind_config_path: Path,\n        source_subvolume: Subvolume,\n        destination_subvolume: Subvolume,\n        boot_stanza_generation: BootStanzaGeneration,\n        icon_command: Optional[IconCommand] = None,\n        inherit_from_state: Optional[State] = None,\n    ) -> BaseMainMigrationStrategy:\n        raise NotImplementedError(\n            \"Cannot instantiate the main migration strategy \"\n            f\"for parameter of type '{type(argument).__name__}'!\"\n        )\n\n    # pylint: disable=unused-argument\n    @migration_strategy.register(BootStanza)\n    @staticmethod\n    def _boot_stanza_overload(\n        boot_stanza: BootStanza,\n        is_latest: bool,\n        refind_config_path: Path,\n        source_subvolume: Subvolume,\n        destination_subvolume: Subvolume,\n        boot_stanza_generation: BootStanzaGeneration,\n        icon_command: Optional[IconCommand] = None,\n        inherit_from_state: Optional[State] = None,\n    ) -> BaseMainMigrationStrategy:\n        return BootStanzaMigrationStrategy(\n            is_latest,\n            refind_config_path,\n            boot_stanza,\n            source_subvolume,\n            destination_subvolume,\n            boot_stanza_generation,\n            none_throws(icon_command),\n        )\n\n    # pylint: disable=unused-argument\n    @migration_strategy.register(SubMenu)\n    @staticmethod\n    def _sub_menu_overload(\n        sub_menu: SubMenu,\n        is_latest: bool,\n        refind_config_path: Path,\n        source_subvolume: Subvolume,\n        destination_subvolume: Subvolume,\n        boot_stanza_generation: BootStanzaGeneration,\n        icon_command: Optional[IconCommand] = None,\n        inherit_from_state: Optional[State] = None,\n    ) -> BaseMainMigrationStrategy:\n        return SubMenuMigrationStrategy(\n            is_latest,\n            refind_config_path,\n            sub_menu,\n            source_subvolume,\n            destination_subvolume,\n            boot_stanza_generation,\n            none_throws(inherit_from_state),\n        )\n"
  },
  {
    "path": "src/refind_btrfs/boot/migrations/migration.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom pathlib import Path\nfrom typing import Collection, Iterator, Optional\n\nfrom more_itertools import first\n\nfrom refind_btrfs.common import BootStanzaGeneration, constants\nfrom refind_btrfs.common.abc.commands import IconCommand\nfrom refind_btrfs.common.exceptions import RefindConfigError\nfrom refind_btrfs.device import BlockDevice, Subvolume\nfrom refind_btrfs.utility.helpers import has_items, none_throws\n\nfrom ..boot_options import BootOptions\nfrom ..boot_stanza import BootStanza\nfrom ..sub_menu import SubMenu\nfrom .main_migration_strategies import MainMigrationFactory\nfrom .state import State\n\n\nclass Migration:\n    def __init__(\n        self,\n        boot_stanza: BootStanza,\n        block_device: BlockDevice,\n        bootable_snapshots: Collection[Subvolume],\n    ) -> None:\n        assert has_items(\n            bootable_snapshots\n        ), \"Parameter 'bootable_snapshots' must contain at least one item!\"\n\n        if not boot_stanza.is_matched_with(block_device):\n            raise RefindConfigError(\"Boot stanza is not matched with the partition!\")\n\n        root_partition = none_throws(block_device.root)\n        filesystem = none_throws(root_partition.filesystem)\n        source_subvolume = none_throws(filesystem.subvolume)\n\n        self._boot_stanza = boot_stanza\n        self._source_subvolume = source_subvolume\n        self._bootable_snapshots = list(bootable_snapshots)\n\n    def migrate(\n        self,\n        refind_config_path: Path,\n        boot_stanza_generation: BootStanzaGeneration,\n        icon_command: IconCommand,\n    ) -> BootStanza:\n        boot_stanza = self._boot_stanza\n        source_subvolume = self._source_subvolume\n        bootable_snapshots = self._bootable_snapshots\n        include_sub_menus = boot_stanza_generation.include_sub_menus\n        latest_migration_result: Optional[State] = None\n        result_sub_menus: list[SubMenu] = []\n\n        for destination_subvolume in bootable_snapshots:\n            is_latest = self._is_latest_snapshot(destination_subvolume)\n            boot_stanza_migration_strategy = MainMigrationFactory.migration_strategy(\n                boot_stanza,\n                is_latest,\n                refind_config_path,\n                source_subvolume,\n                destination_subvolume,\n                boot_stanza_generation,\n                icon_command=icon_command,\n            )\n            migration_result = boot_stanza_migration_strategy.migrate()\n\n            if is_latest:\n                latest_migration_result = migration_result\n            else:\n                result_sub_menus.append(\n                    SubMenu(\n                        migration_result.name,\n                        migration_result.loader_path,\n                        migration_result.initrd_path,\n                        boot_stanza.graphics,\n                        migration_result.boot_options,\n                        BootOptions(constants.EMPTY_STR),\n                        boot_stanza.is_disabled,\n                    )\n                )\n\n            if include_sub_menus:\n                migrated_sub_menus = self._migrate_sub_menus(\n                    refind_config_path,\n                    source_subvolume,\n                    destination_subvolume,\n                    migration_result,\n                    boot_stanza_generation,\n                )\n\n                result_sub_menus.extend(list(migrated_sub_menus))\n\n        boot_stanza_migration_result = none_throws(latest_migration_result)\n\n        return BootStanza(\n            boot_stanza_migration_result.name,\n            boot_stanza.volume,\n            boot_stanza_migration_result.loader_path,\n            boot_stanza_migration_result.initrd_path,\n            boot_stanza_migration_result.icon_path,\n            boot_stanza.os_type,\n            boot_stanza.graphics,\n            none_throws(boot_stanza_migration_result.boot_options),\n            boot_stanza.firmware_bootnum,\n            boot_stanza.is_disabled,\n        ).with_sub_menus(result_sub_menus)\n\n    def _migrate_sub_menus(\n        self,\n        refind_config_path: Path,\n        source_subvolume: Subvolume,\n        destination_subvolume: Subvolume,\n        boot_stanza_result: State,\n        boot_stanza_generation: BootStanzaGeneration,\n    ) -> Iterator[SubMenu]:\n        boot_stanza = self._boot_stanza\n\n        if not boot_stanza.has_sub_menus():\n            return\n\n        current_sub_menus = none_throws(boot_stanza.sub_menus)\n        is_latest = self._is_latest_snapshot(destination_subvolume)\n\n        for sub_menu in current_sub_menus:\n            if sub_menu.can_be_used_for_bootable_snapshot():\n                sub_menu_migration_strategy = MainMigrationFactory.migration_strategy(\n                    sub_menu,\n                    is_latest,\n                    refind_config_path,\n                    source_subvolume,\n                    destination_subvolume,\n                    boot_stanza_generation,\n                    inherit_from_state=boot_stanza_result,\n                )\n                migration_result = sub_menu_migration_strategy.migrate()\n\n                yield SubMenu(\n                    migration_result.name,\n                    migration_result.loader_path,\n                    migration_result.initrd_path,\n                    sub_menu.graphics,\n                    migration_result.boot_options,\n                    none_throws(migration_result.add_boot_options),\n                    sub_menu.is_disabled,\n                )\n\n    def _is_latest_snapshot(self, snapshot: Subvolume) -> bool:\n        bootable_snapshots = self._bootable_snapshots\n        latest_snapshot = first(bootable_snapshots)\n\n        return snapshot == latest_snapshot\n"
  },
  {
    "path": "src/refind_btrfs/boot/migrations/state.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom typing import NamedTuple, Optional\n\nfrom ..boot_options import BootOptions\n\n\nclass State(NamedTuple):\n    name: str\n    loader_path: Optional[str]\n    initrd_path: Optional[str]\n    icon_path: Optional[str]\n    boot_options: Optional[BootOptions]\n    add_boot_options: Optional[BootOptions]\n"
  },
  {
    "path": "src/refind_btrfs/boot/refind_config.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nfrom copy import copy\nfrom itertools import chain\nfrom pathlib import Path\nfrom typing import Collection, Iterable, Iterator, Optional, Self\n\nfrom more_itertools import always_iterable\n\nfrom refind_btrfs.common import BootStanzaGeneration, constants\nfrom refind_btrfs.common.abc import BaseConfig\nfrom refind_btrfs.common.abc.factories import BaseIconCommandFactory\nfrom refind_btrfs.common.enums import ConfigInitializationType\nfrom refind_btrfs.device import BlockDevice, Subvolume\nfrom refind_btrfs.utility.helpers import (\n    has_items,\n    is_none_or_whitespace,\n    none_throws,\n    replace_item_in,\n)\n\nfrom .boot_stanza import BootStanza\nfrom .migrations import Migration\n\n\nclass RefindConfig(BaseConfig):\n    def __init__(self, file_path: Path) -> None:\n        super().__init__(file_path)\n\n        self._boot_stanzas: Optional[list[BootStanza]] = None\n        self._included_configs: Optional[list[RefindConfig]] = None\n\n    def with_boot_stanzas(self, boot_stanzas: Iterable[BootStanza]) -> Self:\n        self._boot_stanzas = list(boot_stanzas)\n\n        return self\n\n    def with_included_configs(self, include_configs: Iterable[RefindConfig]) -> Self:\n        self._included_configs = list(include_configs)\n\n        return self\n\n    def get_boot_stanzas_matched_with(\n        self, block_device: BlockDevice\n    ) -> Iterator[BootStanza]:\n        if self.has_boot_stanzas():\n            yield from (\n                boot_stanza\n                for boot_stanza in none_throws(self.boot_stanzas)\n                if boot_stanza.is_matched_with(block_device)\n            )\n\n        if self.has_included_configs():\n            yield from chain.from_iterable(\n                config.get_boot_stanzas_matched_with(block_device)\n                for config in none_throws(self.included_configs)\n            )\n\n    def get_included_configs_difference_from(\n        self, other: RefindConfig\n    ) -> Optional[Collection[RefindConfig]]:\n        if self.has_included_configs():\n            self_included_configs = none_throws(self.included_configs)\n\n            if not other.has_included_configs():\n                return self_included_configs\n\n            other_included_configs = none_throws(other.included_configs)\n\n            return set(\n                included_config\n                for included_config in self_included_configs\n                if included_config not in other_included_configs\n            )\n\n        return None\n\n    def generate_new_from(\n        self,\n        block_device: BlockDevice,\n        boot_stanzas_with_snapshots: dict[BootStanza, list[Subvolume]],\n        boot_stanza_generation: BootStanzaGeneration,\n        icon_command_factory: BaseIconCommandFactory,\n    ) -> Iterator[RefindConfig]:\n        file_path = self.file_path\n        boot_stanzas = copy(none_throws(self.boot_stanzas))\n        parent_directory = file_path.parent\n        included_configs: list[RefindConfig] = (\n            none_throws(self.included_configs) if self.has_included_configs() else []\n        )\n\n        boot_stanzas.extend(\n            chain.from_iterable(\n                (\n                    none_throws(included_config.boot_stanzas)\n                    for included_config in included_configs\n                    if included_config.has_boot_stanzas()\n                )\n            )\n        )\n\n        icon_command = icon_command_factory.icon_command()\n\n        for boot_stanza in boot_stanzas:\n            bootable_snapshots = boot_stanzas_with_snapshots.get(boot_stanza)\n\n            if has_items(bootable_snapshots):\n                sorted_bootable_snapshots = sorted(\n                    none_throws(bootable_snapshots), reverse=True\n                )\n                migration = Migration(\n                    boot_stanza, block_device, sorted_bootable_snapshots\n                )\n                migrated_boot_stanza = migration.migrate(\n                    file_path, boot_stanza_generation, icon_command\n                )\n                boot_stanza_filename = migrated_boot_stanza.filename\n\n                if not is_none_or_whitespace(boot_stanza_filename):\n                    destination_directory = (\n                        parent_directory / constants.SNAPSHOT_STANZAS_DIR_NAME\n                    )\n                    boot_stanza_config_file_path = (\n                        destination_directory / boot_stanza_filename\n                    )\n                    boot_stanza_config = RefindConfig(\n                        boot_stanza_config_file_path.resolve()\n                    ).with_boot_stanzas(always_iterable(migrated_boot_stanza))\n\n                    if boot_stanza_config not in included_configs:\n                        included_configs.append(boot_stanza_config)\n                    else:\n                        replace_item_in(included_configs, boot_stanza_config)\n\n                    yield boot_stanza_config\n\n        self._included_configs = included_configs\n\n    def has_boot_stanzas(self) -> bool:\n        return has_items(self.boot_stanzas)\n\n    def has_included_configs(self) -> bool:\n        return has_items(self.included_configs)\n\n    def is_of_initialization_type(\n        self, initialization_type: ConfigInitializationType\n    ) -> bool:\n        if super().is_of_initialization_type(initialization_type):\n            return True\n\n        if self.has_included_configs():\n            nongenerated_included_configs = (\n                included_config\n                for included_config in none_throws(self.included_configs)\n                if not included_config.is_generated()\n            )\n\n            return any(\n                included_config.is_of_initialization_type(initialization_type)\n                for included_config in nongenerated_included_configs\n            )\n\n        return False\n\n    def is_generated(self) -> bool:\n        file_path = self.file_path\n        parent_directory = file_path.parent\n\n        return parent_directory.name == constants.SNAPSHOT_STANZAS_DIR_NAME\n\n    @property\n    def boot_stanzas(self) -> Optional[list[BootStanza]]:\n        return self._boot_stanzas\n\n    @property\n    def included_configs(self) -> Optional[list[RefindConfig]]:\n        return self._included_configs\n"
  },
  {
    "path": "src/refind_btrfs/boot/refind_listeners.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom antlr4.error.ErrorListener import ErrorListener\n\nfrom refind_btrfs.common.exceptions import RefindSyntaxError\n\n\nclass RefindErrorListener(ErrorListener):\n    # pylint: disable=unused-argument\n    def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):\n        raise RefindSyntaxError(line, column, msg)\n"
  },
  {
    "path": "src/refind_btrfs/boot/refind_visitors.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom collections import defaultdict\nfrom typing import Any, Callable, DefaultDict, Iterable, NamedTuple, Optional\n\nfrom antlr4 import ParserRuleContext\nfrom more_itertools import always_iterable, only\n\nfrom refind_btrfs.common import constants\nfrom refind_btrfs.common.enums import GraphicsParameter, OSTypeParameter, RefindOption\nfrom refind_btrfs.common.exceptions import RefindConfigError\nfrom refind_btrfs.utility.helpers import checked_cast, try_parse_int\n\nfrom .antlr4 import RefindConfigParser, RefindConfigParserVisitor\nfrom .boot_options import BootOptions\nfrom .boot_stanza import BootStanza\nfrom .sub_menu import SubMenu\n\n\nclass ContextWithVisitor(NamedTuple):\n    child_context_func: Callable[[ParserRuleContext], ParserRuleContext]\n    visitor_func: Callable[[], RefindConfigParserVisitor]\n\n\nclass BootStanzaVisitor(RefindConfigParserVisitor):\n    def visitBoot_stanza(\n        self, ctx: RefindConfigParser.Boot_stanzaContext\n    ) -> BootStanza:\n        menu_entry_context = ctx.menu_entry()\n        menu_entry = menu_entry_context.accept(MenuEntryVisitor())\n        main_options = OptionVisitor.map_to_options_dict(\n            checked_cast(list[ParserRuleContext], ctx.main_option())\n        )\n        volume = only(always_iterable(main_options.get(RefindOption.VOLUME)))\n        loader = only(always_iterable(main_options.get(RefindOption.LOADER)))\n        initrd = only(always_iterable(main_options.get(RefindOption.INITRD)))\n        icon = only(always_iterable(main_options.get(RefindOption.ICON)))\n        os_type = only(always_iterable(main_options.get(RefindOption.OS_TYPE)))\n        graphics = only(always_iterable(main_options.get(RefindOption.GRAPHICS)))\n        boot_options = only(\n            always_iterable(main_options.get(RefindOption.BOOT_OPTIONS))\n        )\n        firmware_bootnum = only(\n            always_iterable(main_options.get(RefindOption.FIRMWARE_BOOTNUM))\n        )\n        disabled = only(\n            always_iterable(main_options.get(RefindOption.DISABLED)), default=False\n        )\n        sub_menus = always_iterable(main_options.get(RefindOption.SUB_MENU_ENTRY))\n\n        return BootStanza(\n            menu_entry,\n            volume,\n            loader,\n            initrd,\n            icon,\n            os_type,\n            graphics,\n            BootOptions(boot_options),\n            firmware_bootnum,\n            disabled,\n        ).with_sub_menus(sub_menus)\n\n\nclass MenuEntryVisitor(RefindConfigParserVisitor):\n    def visitMenu_entry(self, ctx: RefindConfigParser.Menu_entryContext) -> str:\n        token = ctx.STRING()\n\n        return token.getText()\n\n\nclass OptionVisitor(RefindConfigParserVisitor):\n    def __init__(self) -> None:\n        self._main_option_mappings = {\n            RefindOption.VOLUME: ContextWithVisitor(\n                RefindConfigParser.Main_optionContext.volume, VolumeVisitor\n            ),\n            RefindOption.LOADER: ContextWithVisitor(\n                RefindConfigParser.Main_optionContext.loader, LoaderVisitor\n            ),\n            RefindOption.INITRD: ContextWithVisitor(\n                RefindConfigParser.Main_optionContext.main_initrd, InitrdVisitor\n            ),\n            RefindOption.ICON: ContextWithVisitor(\n                RefindConfigParser.Main_optionContext.icon, IconVisitor\n            ),\n            RefindOption.OS_TYPE: ContextWithVisitor(\n                RefindConfigParser.Main_optionContext.os_type, OsTypeVisitor\n            ),\n            RefindOption.GRAPHICS: ContextWithVisitor(\n                RefindConfigParser.Main_optionContext.graphics, GraphicsVisitor\n            ),\n            RefindOption.BOOT_OPTIONS: ContextWithVisitor(\n                RefindConfigParser.Main_optionContext.main_boot_options,\n                BootOptionsVisitor,\n            ),\n            RefindOption.FIRMWARE_BOOTNUM: ContextWithVisitor(\n                RefindConfigParser.Main_optionContext.firmware_bootnum,\n                FirmwareBootnumVisitor,\n            ),\n            RefindOption.DISABLED: ContextWithVisitor(\n                RefindConfigParser.Main_optionContext.disabled, DisabledVisitor\n            ),\n            RefindOption.SUB_MENU_ENTRY: ContextWithVisitor(\n                RefindConfigParser.Main_optionContext.sub_menu, SubMenuVisitor\n            ),\n        }\n        self._sub_option_mappings = {\n            RefindOption.LOADER: ContextWithVisitor(\n                RefindConfigParser.Sub_optionContext.loader, LoaderVisitor\n            ),\n            RefindOption.INITRD: ContextWithVisitor(\n                RefindConfigParser.Sub_optionContext.sub_initrd, InitrdVisitor\n            ),\n            RefindOption.GRAPHICS: ContextWithVisitor(\n                RefindConfigParser.Sub_optionContext.graphics, GraphicsVisitor\n            ),\n            RefindOption.BOOT_OPTIONS: ContextWithVisitor(\n                RefindConfigParser.Sub_optionContext.sub_boot_options,\n                BootOptionsVisitor,\n            ),\n            RefindOption.ADD_BOOT_OPTIONS: ContextWithVisitor(\n                RefindConfigParser.Sub_optionContext.add_boot_options,\n                BootOptionsVisitor,\n            ),\n            RefindOption.DISABLED: ContextWithVisitor(\n                RefindConfigParser.Sub_optionContext.disabled, DisabledVisitor\n            ),\n        }\n\n    @classmethod\n    def map_to_options_dict(\n        cls, option_contexts: Iterable[ParserRuleContext]\n    ) -> DefaultDict[RefindOption, list[Any]]:\n        option_visitor = cls()\n        result = defaultdict(list)\n\n        for option_context in option_contexts:\n            option_tuple = option_context.accept(option_visitor)\n\n            if option_tuple is not None:\n                key = checked_cast(RefindOption, option_tuple[0])\n                value = option_tuple[1]\n\n                result[key].append(value)\n\n        return result\n\n    def visitMain_option(\n        self, ctx: RefindConfigParser.Main_optionContext\n    ) -> Optional[tuple[RefindOption, Any]]:\n        return OptionVisitor._map_to_option_tuple(ctx, self._main_option_mappings)\n\n    def visitSub_option(\n        self, ctx: RefindConfigParser.Sub_optionContext\n    ) -> Optional[tuple[RefindOption, Any]]:\n        return OptionVisitor._map_to_option_tuple(ctx, self._sub_option_mappings)\n\n    @staticmethod\n    def _map_to_option_tuple(\n        ctx: ParserRuleContext, mappings: dict[RefindOption, ContextWithVisitor]\n    ) -> Optional[tuple[RefindOption, Any]]:\n        for key, value in mappings.items():\n            option_context = value.child_context_func(ctx)\n\n            if option_context is not None:\n                visitor = value.visitor_func()\n\n                return key, option_context.accept(visitor)\n\n        return None\n\n\nclass SubMenuVisitor(RefindConfigParserVisitor):\n    def visitSub_menu(self, ctx: RefindConfigParser.Sub_menuContext) -> SubMenu:\n        menu_entry_context = ctx.menu_entry()\n        menu_entry = menu_entry_context.accept(MenuEntryVisitor())\n        sub_options = OptionVisitor.map_to_options_dict(\n            checked_cast(list[ParserRuleContext], ctx.sub_option())\n        )\n        loader = only(always_iterable(sub_options.get(RefindOption.LOADER)))\n        initrd = only(always_iterable(sub_options.get(RefindOption.INITRD)))\n        graphics = only(always_iterable(sub_options.get(RefindOption.GRAPHICS)))\n        boot_options = only(always_iterable(sub_options.get(RefindOption.BOOT_OPTIONS)))\n        add_boot_options = only(\n            always_iterable(sub_options.get(RefindOption.ADD_BOOT_OPTIONS))\n        )\n        disabled = only(\n            always_iterable(sub_options.get(RefindOption.DISABLED)), default=False\n        )\n\n        return SubMenu(\n            menu_entry,\n            loader,\n            initrd,\n            graphics,\n            BootOptions(boot_options) if boot_options is not None else None,\n            BootOptions(add_boot_options),\n            disabled,\n        )\n\n\nclass VolumeVisitor(RefindConfigParserVisitor):\n    def visitVolume(self, ctx: RefindConfigParser.VolumeContext) -> str:\n        if ctx is not None:\n            token = ctx.STRING()\n\n            return token.getText()\n\n        return None\n\n\nclass LoaderVisitor(RefindConfigParserVisitor):\n    def visitLoader(self, ctx: RefindConfigParser.LoaderContext) -> str:\n        token = ctx.STRING()\n\n        return token.getText()\n\n\nclass InitrdVisitor(RefindConfigParserVisitor):\n    def visitMain_initrd(self, ctx: RefindConfigParser.Main_initrdContext) -> str:\n        token = ctx.STRING()\n\n        return token.getText()\n\n    def visitSub_initrd(self, ctx: RefindConfigParser.Sub_initrdContext) -> str:\n        token = ctx.STRING()\n\n        if token is not None:\n            return token.getText()\n\n        return constants.EMPTY_STR\n\n\nclass IconVisitor(RefindConfigParserVisitor):\n    def visitIcon(self, ctx: RefindConfigParser.IconContext) -> str:\n        token = ctx.STRING()\n\n        return token.getText()\n\n\nclass OsTypeVisitor(RefindConfigParserVisitor):\n    def visitOs_type(self, ctx: RefindConfigParser.Os_typeContext) -> str:\n        token = ctx.OS_TYPE_PARAMETER()\n        text = token.getText()\n        os_type_options = [\n            os_type_parameter.value for os_type_parameter in OSTypeParameter\n        ]\n\n        if text not in os_type_options:\n            raise RefindConfigError(f\"Unexpected 'os_type' option - '{text}'!\")\n\n        return text\n\n\nclass GraphicsVisitor(RefindConfigParserVisitor):\n    def visitGraphics(self, ctx: RefindConfigParser.GraphicsContext) -> bool:\n        token = ctx.GRAPHICS_PARAMETER()\n        text = token.getText()\n\n        if text == GraphicsParameter.ON.value:\n            return True\n\n        if text == GraphicsParameter.OFF.value:\n            return False\n\n        raise RefindConfigError(f\"Unexpected 'graphics' option - '{text}'!\")\n\n\nclass BootOptionsVisitor(RefindConfigParserVisitor):\n    def visitMain_boot_options(\n        self, ctx: RefindConfigParser.Main_boot_optionsContext\n    ) -> str:\n        token = ctx.STRING()\n\n        return token.getText()\n\n    def visitSub_boot_options(\n        self, ctx: RefindConfigParser.Sub_boot_optionsContext\n    ) -> str:\n        token = ctx.STRING()\n\n        if token is not None:\n            return token.getText()\n\n        return constants.EMPTY_STR\n\n    def visitAdd_boot_options(\n        self, ctx: RefindConfigParser.Add_boot_optionsContext\n    ) -> str:\n        token = ctx.STRING()\n\n        return token.getText()\n\n\nclass FirmwareBootnumVisitor(RefindConfigParserVisitor):\n    def visitFirmware_bootnum(\n        self, ctx: RefindConfigParser.Firmware_bootnumContext\n    ) -> int:\n        token = ctx.HEX_INTEGER()\n        text = token.getText()\n        firmware_bootnum = try_parse_int(text, 16)\n\n        if firmware_bootnum is None:\n            raise RefindConfigError(f\"Unexpected 'firmware_bootnum' option - '{text}'!\")\n\n        return firmware_bootnum\n\n\nclass DisabledVisitor(RefindConfigParserVisitor):\n    def visitDisabled(self, ctx: RefindConfigParser.DisabledContext) -> bool:\n        return True\n\n\nclass IncludeVisitor(RefindConfigParserVisitor):\n    def visitInclude(self, ctx: RefindConfigParser.IncludeContext) -> str:\n        token = ctx.STRING()\n\n        return token.getText()\n"
  },
  {
    "path": "src/refind_btrfs/boot/sub_menu.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom functools import cached_property\nfrom typing import Iterator, Optional, Set\n\nfrom refind_btrfs.common import constants\nfrom refind_btrfs.common.enums import (\n    BootFilePathSource,\n    GraphicsParameter,\n    RefindOption,\n)\nfrom refind_btrfs.device import BlockDevice\nfrom refind_btrfs.utility.helpers import (\n    is_empty,\n    is_none_or_whitespace,\n    none_throws,\n    strip_quotes,\n)\n\nfrom .boot_options import BootOptions\n\n\nclass SubMenu:\n    def __init__(\n        self,\n        name: str,\n        loader_path: Optional[str],\n        initrd_path: Optional[str],\n        graphics: Optional[bool],\n        boot_options: Optional[BootOptions],\n        add_boot_options: BootOptions,\n        is_disabled: bool,\n    ) -> None:\n        self._name = name\n        self._loader_path = loader_path\n        self._initrd_path = initrd_path\n        self._graphics = graphics\n        self._boot_options = boot_options\n        self._add_boot_options = add_boot_options\n        self._is_disabled = is_disabled\n\n    def __str__(self) -> str:\n        main_indent = constants.TAB\n        option_indent = main_indent * 2\n        result: list[str] = []\n\n        name = self.name\n\n        result.append(f\"{main_indent}{RefindOption.SUB_MENU_ENTRY.value} {name} {{\")\n\n        loader_path = self.loader_path\n\n        if not is_none_or_whitespace(loader_path):\n            result.append(f\"{option_indent}{RefindOption.LOADER.value} {loader_path}\")\n\n        initrd_path = self.initrd_path\n\n        if not is_none_or_whitespace(initrd_path):\n            result.append(f\"{option_indent}{RefindOption.INITRD.value} {initrd_path}\")\n\n        graphics = self.graphics\n\n        if graphics is not None:\n            value = (\n                GraphicsParameter.ON.value if graphics else GraphicsParameter.OFF.value\n            )\n            result.append(f\"{option_indent}{RefindOption.GRAPHICS.value} {value}\")\n\n        boot_options = self.boot_options\n\n        if not boot_options is None:\n            boot_options_str = str(boot_options)\n\n            if not is_none_or_whitespace(boot_options_str):\n                result.append(\n                    f\"{option_indent}{RefindOption.BOOT_OPTIONS.value} {boot_options_str}\"\n                )\n\n        add_boot_options_str = str(self.add_boot_options)\n\n        if not is_none_or_whitespace(add_boot_options_str):\n            result.append(\n                f\"{option_indent}{RefindOption.ADD_BOOT_OPTIONS.value} {add_boot_options_str}\"\n            )\n\n        is_disabled = self.is_disabled\n\n        if is_disabled:\n            result.append(f\"{option_indent}{RefindOption.DISABLED.value}\")\n\n        result.append(f\"{main_indent}}}\")\n\n        return constants.NEWLINE.join(result)\n\n    def is_matched_with(self, block_device: BlockDevice) -> bool:\n        boot_options = self.boot_options\n\n        return (\n            boot_options.is_matched_with(block_device)\n            if boot_options is not None\n            else False\n        )\n\n    def can_be_used_for_bootable_snapshot(self) -> bool:\n        loader_path = self.loader_path\n        initrd_path = self.initrd_path\n        boot_options = self.boot_options\n        is_disabled = self.is_disabled\n\n        return (\n            is_none_or_whitespace(loader_path)\n            and (initrd_path is None or not is_empty(initrd_path))\n            and boot_options is None\n            and not is_disabled\n        )\n\n    def _get_all_boot_file_paths(\n        self,\n    ) -> Iterator[tuple[BootFilePathSource, str]]:\n        source = BootFilePathSource.SUB_MENU\n        is_disabled = self.is_disabled\n\n        if not is_disabled:\n            loader_path = self.loader_path\n            initrd_path = self.initrd_path\n            boot_options = self.boot_options\n            add_boot_options = self.add_boot_options\n\n            if not is_none_or_whitespace(loader_path):\n                yield (source, none_throws(loader_path))\n\n            if not is_none_or_whitespace(initrd_path):\n                yield (source, none_throws(initrd_path))\n\n            if not boot_options is None:\n                yield from (\n                    (source, initrd_option)\n                    for initrd_option in boot_options.initrd_options\n                )\n\n            yield from (\n                (source, initrd_option)\n                for initrd_option in add_boot_options.initrd_options\n            )\n\n    @property\n    def name(self) -> str:\n        return self._name\n\n    @property\n    def normalized_name(self) -> str:\n        return strip_quotes(self.name)\n\n    @property\n    def loader_path(self) -> Optional[str]:\n        return self._loader_path\n\n    @property\n    def initrd_path(self) -> Optional[str]:\n        return self._initrd_path\n\n    @property\n    def graphics(self) -> Optional[bool]:\n        return self._graphics\n\n    @property\n    def boot_options(self) -> Optional[BootOptions]:\n        return self._boot_options\n\n    @property\n    def add_boot_options(self) -> BootOptions:\n        return self._add_boot_options\n\n    @property\n    def is_disabled(self) -> bool:\n        return self._is_disabled\n\n    @cached_property\n    def all_boot_file_paths(self) -> Set[tuple[BootFilePathSource, str]]:\n        return set(self._get_all_boot_file_paths())\n"
  },
  {
    "path": "src/refind_btrfs/common/__init__.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom .boot_files_check_result import BootFilesCheckResult\nfrom .checkable_observer import CheckableObserver\nfrom .configurable_mixin import ConfigurableMixin\nfrom .package_config import (\n    BootStanzaGeneration,\n    BtrfsLogo,\n    Icon,\n    PackageConfig,\n    SnapshotManipulation,\n    SnapshotSearch,\n)\n"
  },
  {
    "path": "src/refind_btrfs/common/abc/__init__.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom .base_config import BaseConfig\nfrom .base_runner import BaseRunner\n"
  },
  {
    "path": "src/refind_btrfs/common/abc/base_config.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nfrom abc import ABC\nfrom os import stat_result\nfrom pathlib import Path\nfrom typing import Any, Optional, Self\n\nfrom refind_btrfs.common.enums import ConfigInitializationType\nfrom refind_btrfs.utility.helpers import checked_cast, none_throws\n\n\nclass BaseConfig(ABC):\n    def __init__(self, file_path: Path) -> None:\n        self._file_path = file_path\n        self._file_stat: Optional[stat_result] = None\n        self._initialization_type: Optional[ConfigInitializationType] = None\n\n        self.refresh_file_stat()\n\n    def __eq__(self, other: object) -> bool:\n        if self is other:\n            return True\n\n        if isinstance(other, BaseConfig):\n            self_file_path_resolved = self.file_path.resolve()\n            other_file_path_resolved = other.file_path.resolve()\n\n            return self_file_path_resolved == other_file_path_resolved\n\n        return False\n\n    def __hash__(self) -> int:\n        return hash(self.file_path.resolve())\n\n    def __getstate__(self) -> dict[str, Any]:\n        state = self.__dict__.copy()\n        initialization_type_key = \"_initialization_type\"\n\n        if initialization_type_key in state:\n            del state[initialization_type_key]\n\n        return state\n\n    def with_initialization_type(\n        self, initialization_type: ConfigInitializationType\n    ) -> Self:\n        self._initialization_type = initialization_type\n\n        return self\n\n    def refresh_file_stat(self):\n        file_path = self.file_path\n\n        if file_path.exists():\n            self._file_stat = file_path.stat()\n\n    def is_modified(self, actual_file_path: Path) -> bool:\n        current_file_path = self.file_path\n\n        if current_file_path != actual_file_path:\n            return True\n\n        current_file_stat = none_throws(self.file_stat)\n\n        if actual_file_path.exists():\n            actual_file_stat = actual_file_path.stat()\n\n            return current_file_stat.st_mtime != actual_file_stat.st_mtime\n\n        return True\n\n    def is_of_initialization_type(\n        self, initialization_type: ConfigInitializationType\n    ) -> bool:\n        return self.initialization_type == initialization_type\n\n    @property\n    def file_path(self) -> Path:\n        return self._file_path\n\n    @property\n    def file_stat(self) -> Optional[stat_result]:\n        return self._file_stat\n\n    @property\n    def initialization_type(self) -> Optional[ConfigInitializationType]:\n        return self._initialization_type\n"
  },
  {
    "path": "src/refind_btrfs/common/abc/base_runner.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom abc import ABC, abstractmethod\n\n\nclass BaseRunner(ABC):\n    @abstractmethod\n    def run(self) -> int:\n        pass\n"
  },
  {
    "path": "src/refind_btrfs/common/abc/commands/__init__.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom .device_command import DeviceCommand\nfrom .icon_command import IconCommand\nfrom .subvolume_command import SubvolumeCommand\n"
  },
  {
    "path": "src/refind_btrfs/common/abc/commands/device_command.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom abc import ABC, abstractmethod\nfrom functools import singledispatchmethod\nfrom typing import Any, Iterator\n\nfrom refind_btrfs.device import BlockDevice, PartitionTable, Subvolume\n\n\nclass DeviceCommand(ABC):\n    @abstractmethod\n    def get_block_devices(self) -> Iterator[BlockDevice]:\n        pass\n\n    @singledispatchmethod\n    def get_partition_table_for(self, argument: Any) -> PartitionTable:\n        raise NotImplementedError(\n            f\"Cannot get the partition table for parameter of type '{type(argument).__name__}'!\"\n        )\n\n    @abstractmethod\n    def save_partition_table(self, partition_table: PartitionTable) -> None:\n        pass\n\n    @get_partition_table_for.register(BlockDevice)\n    def _block_device_overload(self, block_device: BlockDevice) -> PartitionTable:\n        return self._block_device_partition_table(block_device)\n\n    @get_partition_table_for.register(Subvolume)\n    def _subvolume_overload(self, subvolume: Subvolume) -> PartitionTable:\n        return self._subvolume_partition_table(subvolume)\n\n    @abstractmethod\n    def _block_device_partition_table(\n        self, block_device: BlockDevice\n    ) -> PartitionTable:\n        pass\n\n    @abstractmethod\n    def _subvolume_partition_table(self, subvolume: Subvolume) -> PartitionTable:\n        pass\n"
  },
  {
    "path": "src/refind_btrfs/common/abc/commands/icon_command.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\n\nfrom refind_btrfs.common import BtrfsLogo\n\n\nclass IconCommand(ABC):\n    @abstractmethod\n    def validate_custom_icon(\n        self, refind_config_path: Path, source_icon_path: Path, custom_icon_path: Path\n    ) -> Path:\n        pass\n\n    @abstractmethod\n    def embed_btrfs_logo_into_source_icon(\n        self, refind_config_path: Path, source_icon_path: Path, btrfs_logo: BtrfsLogo\n    ) -> Path:\n        pass\n"
  },
  {
    "path": "src/refind_btrfs/common/abc/commands/subvolume_command.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\nfrom typing import Iterator, Optional\n\nfrom refind_btrfs.device import Subvolume\n\n\nclass SubvolumeCommand(ABC):\n    @abstractmethod\n    def get_subvolume_from(self, filesystem_path: Path) -> Optional[Subvolume]:\n        pass\n\n    @abstractmethod\n    def get_all_source_snapshots_for(self, parent: Subvolume) -> Iterator[Subvolume]:\n        pass\n\n    @abstractmethod\n    def get_all_destination_snapshots(self) -> Iterator[Subvolume]:\n        pass\n\n    @abstractmethod\n    def get_bootable_snapshot_from(self, source: Subvolume) -> Subvolume:\n        pass\n\n    @abstractmethod\n    def delete_snapshot(self, snapshot: Subvolume) -> None:\n        pass\n"
  },
  {
    "path": "src/refind_btrfs/common/abc/factories/__init__.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom .base_device_command_factory import BaseDeviceCommandFactory\nfrom .base_icon_command_factory import BaseIconCommandFactory\nfrom .base_logger_factory import BaseLoggerFactory\nfrom .base_subvolume_command_factory import BaseSubvolumeCommandFactory\n"
  },
  {
    "path": "src/refind_btrfs/common/abc/factories/base_device_command_factory.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nfrom abc import ABC, abstractmethod\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from ..commands import DeviceCommand\n\n\nclass BaseDeviceCommandFactory(ABC):\n    @abstractmethod\n    def physical_device_command(self) -> DeviceCommand:\n        pass\n\n    @abstractmethod\n    def live_device_command(self) -> DeviceCommand:\n        pass\n\n    @abstractmethod\n    def static_device_command(self) -> DeviceCommand:\n        pass\n"
  },
  {
    "path": "src/refind_btrfs/common/abc/factories/base_icon_command_factory.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nfrom abc import ABC, abstractmethod\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from ..commands import IconCommand\n\n\nclass BaseIconCommandFactory(ABC):\n    @abstractmethod\n    def icon_command(self) -> IconCommand:\n        pass\n"
  },
  {
    "path": "src/refind_btrfs/common/abc/factories/base_logger_factory.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport logging\nfrom abc import ABC, abstractmethod\nfrom logging import Handler, Logger\n\nfrom refind_btrfs.utility import LevelAwareFormatter\n\n\nclass BaseLoggerFactory(ABC):\n    def logger(self, name: str) -> Logger:\n        logger = logging.getLogger(name)\n\n        if not logger.hasHandlers():\n            logging_handler = self.get_handler()\n            formatter = LevelAwareFormatter()\n\n            logger.propagate = False\n            logger.setLevel(logging.INFO)\n            logging_handler.setLevel(logging.INFO)\n            logging_handler.setFormatter(formatter)\n            logger.addHandler(logging_handler)\n\n        return logger\n\n    @abstractmethod\n    def get_handler(self) -> Handler:\n        pass\n"
  },
  {
    "path": "src/refind_btrfs/common/abc/factories/base_subvolume_command_factory.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nfrom abc import ABC, abstractmethod\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from ..commands import SubvolumeCommand\n\n\nclass BaseSubvolumeCommandFactory(ABC):\n    @abstractmethod\n    def subvolume_command(self) -> SubvolumeCommand:\n        pass\n"
  },
  {
    "path": "src/refind_btrfs/common/abc/providers/__init__.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom .base_package_config_provider import BasePackageConfigProvider\nfrom .base_persistence_provider import BasePersistenceProvider\nfrom .base_refind_config_provider import BaseRefindConfigProvider\n"
  },
  {
    "path": "src/refind_btrfs/common/abc/providers/base_package_config_provider.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nfrom abc import ABC, abstractmethod\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from refind_btrfs.common import PackageConfig\n\n\nclass BasePackageConfigProvider(ABC):\n    @abstractmethod\n    def get_config(self) -> PackageConfig:\n        pass\n"
  },
  {
    "path": "src/refind_btrfs/common/abc/providers/base_persistence_provider.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Optional\n\nif TYPE_CHECKING:\n    from refind_btrfs.boot import RefindConfig\n    from refind_btrfs.common import PackageConfig\n    from refind_btrfs.state_management.model import ProcessingResult\n\n\nclass BasePersistenceProvider(ABC):\n    @abstractmethod\n    def get_package_config(self) -> Optional[PackageConfig]:\n        pass\n\n    @abstractmethod\n    def save_package_config(self, value: PackageConfig) -> None:\n        pass\n\n    @abstractmethod\n    def get_refind_config(self, file_path: Path) -> Optional[RefindConfig]:\n        pass\n\n    @abstractmethod\n    def save_refind_config(self, value: RefindConfig) -> None:\n        pass\n\n    @abstractmethod\n    def get_previous_run_result(self) -> ProcessingResult:\n        pass\n\n    @abstractmethod\n    def save_current_run_result(self, value: ProcessingResult) -> None:\n        pass\n"
  },
  {
    "path": "src/refind_btrfs/common/abc/providers/base_refind_config_provider.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nfrom abc import ABC, abstractmethod\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from refind_btrfs.boot import RefindConfig\n    from refind_btrfs.device import Partition\n\n\nclass BaseRefindConfigProvider(ABC):\n    @abstractmethod\n    def get_config(self, partition: Partition) -> RefindConfig:\n        pass\n\n    @abstractmethod\n    def save_config(self, config: RefindConfig) -> None:\n        pass\n\n    @abstractmethod\n    def append_to_config(self, config: RefindConfig) -> None:\n        pass\n"
  },
  {
    "path": "src/refind_btrfs/common/boot_files_check_result.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\n\nfrom typing import NamedTuple\n\nfrom refind_btrfs.utility.helpers import has_items\n\n\nclass BootFilesCheckResult(NamedTuple):\n    required_by_boot_stanza_name: str\n    expected_logical_path: str\n    matched_boot_files: list[str]\n    unmatched_boot_files: list[str]\n\n    def has_unmatched_boot_files(self) -> bool:\n        return has_items(self.unmatched_boot_files)\n"
  },
  {
    "path": "src/refind_btrfs/common/checkable_observer.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom typing import Optional\n\nfrom watchdog.observers import Observer\nfrom watchdog.observers.api import DEFAULT_OBSERVER_TIMEOUT\n\n\nclass CheckableObserver(Observer):\n    def __init__(self):\n        super().__init__(timeout=DEFAULT_OBSERVER_TIMEOUT)\n\n        self._exception: Optional[Exception] = None\n\n    # pylint: disable=raising-bad-type\n    def check(self) -> None:\n        exception = self._exception\n\n        if exception is not None:\n            raise exception\n"
  },
  {
    "path": "src/refind_btrfs/common/configurable_mixin.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom refind_btrfs.common.abc.providers import BasePackageConfigProvider\n\nif TYPE_CHECKING:\n    from refind_btrfs.common import PackageConfig\n\n\nclass ConfigurableMixin:\n    def __init__(self, package_config_provider: BasePackageConfigProvider) -> None:\n        self._package_config_provider = package_config_provider\n\n    @property\n    def package_config(self) -> PackageConfig:\n        package_config_provider = self._package_config_provider\n\n        return package_config_provider.get_config()\n"
  },
  {
    "path": "src/refind_btrfs/common/constants.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom pathlib import Path\nfrom uuid import UUID\n\nPACKAGE_NAME = \"refind-btrfs\"\n\nROOT_UID = 0\n\nEX_NOT_OK = 1\nEX_CTRL_C_INTERRUPT = 130\n\nNOTIFICATION_READY = \"READY=1\"\nNOTIFICATION_STOPPING = \"STOPPING=1\"\nNOTIFICATION_STATUS = \"STATUS={0}\"\nNOTIFICATION_ERRNO = \"ERRNO={0}\"\n\nMESSAGE_CTRL_C_INTERRUPT = \"Ctrl+C interrupt detected, exiting...\"\nMESSAGE_UNEXPECTED_ERROR = \"An unexpected error happened, exiting...\"\n\nWATCH_TIMEOUT = 1\nBACKGROUND_MODE_PID_NAME = f\"{PACKAGE_NAME}-watchdog\"\n\nMTAB_PT_TYPE = \"mtab\"\nFSTAB_PT_TYPE = \"fstab\"\n\nESP_PART_TYPE_CODE = 0xEF\nESP_PART_TYPE_UUID = UUID(hex=\"c12a7328-f81f-11d2-ba4b-00a0c93ec93b\")\n\nESP_FS_TYPE = \"vfat\"\nBTRFS_TYPE = \"btrfs\"\n\nSNAPSHOT_SELECTION_COUNT_INFINITY = \"inf\"\nSNAPSHOTS_ROOT_DIR_PERMISSIONS = 0o750\n\nPARAMETERIZED_OPTION_SEPARATOR = \"=\"\nBOOT_OPTION_SEPARATOR = \" \"\nCOLUMN_SEPARATOR = \",\"\n\nROOT_PREFIX = f\"root{PARAMETERIZED_OPTION_SEPARATOR}\"\nROOTFLAGS_PREFIX = f\"rootflags{PARAMETERIZED_OPTION_SEPARATOR}\"\nINITRD_PREFIX = f\"initrd{PARAMETERIZED_OPTION_SEPARATOR}\"\nSUBVOL_OPTION = \"subvol\"\nSUBVOLID_OPTION = \"subvolid\"\n\nSPACE = \" \"\nTAB = SPACE * 4\nSINGLE_QUOTE = \"'\"\nDOUBLE_QUOTE = '\"'\nBACKSLASH = \"\\\\\"\nFORWARD_SLASH = \"/\"\nNEWLINE = \"\\n\"\nEMPTY_STR = \"\"\nEMPTY_HEX_UUID = \"00000000-0000-0000-0000-000000000000\"\nEMPTY_UUID = UUID(hex=EMPTY_HEX_UUID)\nEMPTY_PATH = Path(\".\")\nDEFAULT_ITEMS_SEPARATOR = COLUMN_SEPARATOR + SPACE\nDEFAULT_DIR_SEPARATOR_REPLACEMENT: tuple[str, str] = (BACKSLASH, FORWARD_SLASH)\n\nWHITESPACE_PATTERN = r\"\\s+\"\nINCLUDE_OPTION_PATTERN = r\"^include .+$\"\nPARAMETERIZED_OPTION_PREFIX_PATTERN = r\"^\\S+=\"\nDIR_SEPARATOR_PATTERN = f\"({BACKSLASH * 2}|{FORWARD_SLASH})\"\nSUBVOLUME_NAME_PATTERN = (\n    r\"((rw|ro)(subvol|snap))_\\d{4}-\\d{2}-\\d{2}_\\d{2}-\\d{2}-\\d{2}_ID\\d+\"\n)\n\nCONFIG_FILE_EXTENSION = \".conf\"\nCONFIG_FILENAME = PACKAGE_NAME + CONFIG_FILE_EXTENSION\nSNAPSHOT_STANZAS_DIR_NAME = \"btrfs-snapshot-stanzas\"\nICONS_DIR = \"icons\"\n\nROOT_DIR = Path(\"/\")\nBOOT_DIR = Path(\"boot\")\nETC_DIR = Path(\"etc\")\nVAR_DIR = Path(\"var\")\nLIB_DIR = Path(\"lib\")\n\nFSTAB_FILE = ETC_DIR / \"fstab\"\nPACKAGE_CONFIG_FILE = ROOT_DIR / ETC_DIR / CONFIG_FILENAME\nPACKAGE_LIB_DIR = ROOT_DIR / VAR_DIR / LIB_DIR / PACKAGE_NAME\nBTRFS_LOGOS_DIR = PACKAGE_LIB_DIR / ICONS_DIR / \"btrfs_logo\"\nDB_FILE = PACKAGE_LIB_DIR / \"local_db\"\nDB_ITEM_VERSION_SUFFIX = \"version\"\n"
  },
  {
    "path": "src/refind_btrfs/common/enums.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom enum import Enum, auto, unique\nfrom typing import Any\n\n\nclass AutoNameToLower(Enum):\n    # pylint: disable=arguments-differ, unused-argument\n    @staticmethod\n    def _generate_next_value_(\n        name: str, start: int, count: int, last_values: list[Any]\n    ) -> Any:\n        return name.lower()\n\n\n@unique\nclass RunMode(AutoNameToLower):\n    ONE_TIME = \"one-time\"\n    BACKGROUND = auto()\n\n\n@unique\nclass LsblkJsonKey(AutoNameToLower):\n    BLOCKDEVICES = auto()\n    CHILDREN = auto()\n\n\n@unique\nclass LsblkColumn(Enum):\n    DEVICE_NAME = \"name\"\n    DEVICE_TYPE = \"type\"\n    MAJOR_MINOR = \"maj:min\"\n    PTABLE_UUID = \"ptuuid\"\n    PTABLE_TYPE = \"pttype\"\n    PART_UUID = \"partuuid\"\n    PART_TYPE = \"parttype\"\n    PART_LABEL = \"partlabel\"\n    FS_UUID = \"uuid\"\n    FS_TYPE = \"fstype\"\n    FS_LABEL = \"label\"\n    FS_MOUNT_POINT = \"mountpoint\"\n\n\n@unique\nclass FindmntJsonKey(AutoNameToLower):\n    FILESYSTEMS = auto()\n\n\n@unique\nclass FindmntColumn(Enum):\n    DEVICE_NAME = \"source\"\n    PART_UUID = \"partuuid\"\n    PART_LABEL = \"partlabel\"\n    FS_UUID = \"uuid\"\n    FS_TYPE = \"fstype\"\n    FS_LABEL = \"label\"\n    FS_MOUNT_POINT = \"target\"\n    FS_MOUNT_OPTIONS = \"options\"\n\n\n@unique\nclass FstabColumn(Enum):\n    DEVICE_NAME = 0\n    FS_MOUNT_POINT = 1\n    FS_TYPE = 2\n    FS_MOUNT_OPTIONS = 3\n    FS_DUMP = 4\n    FS_FSCK = 5\n\n\n@unique\nclass PathRelation(Enum):\n    UNRELATED = 0\n    SAME = 1\n    FIRST_NESTED_IN_SECOND = 2\n    SECOND_NESTED_IN_FIRST = 3\n\n\n@unique\nclass ConfigInitializationType(Enum):\n    PARSED = 0\n    PERSISTED = 1\n\n\n@unique\nclass TopLevelConfigKey(AutoNameToLower):\n    EXIT_IF_ROOT_IS_SNAPSHOT = auto()\n    EXIT_IF_NO_CHANGES_ARE_DETECTED = auto()\n    ESP_UUID = auto()\n    SNAPSHOT_SEARCH = \"snapshot-search\"\n    SNAPSHOT_MANIPULATION = \"snapshot-manipulation\"\n    BOOT_STANZA_GENERATION = \"boot-stanza-generation\"\n\n\n@unique\nclass SnapshotSearchConfigKey(AutoNameToLower):\n    DIRECTORY = auto()\n    IS_NESTED = auto()\n    MAX_DEPTH = auto()\n\n\n@unique\nclass SnapshotManipulationConfigKey(AutoNameToLower):\n    SELECTION_COUNT = auto()\n    MODIFY_READ_ONLY_FLAG = auto()\n    DESTINATION_DIRECTORY = auto()\n    CLEANUP_EXCLUSION = auto()\n\n\n@unique\nclass BootStanzaGenerationConfigKey(AutoNameToLower):\n    REFIND_CONFIG = auto()\n    INCLUDE_PATHS = auto()\n    INCLUDE_SUB_MENUS = auto()\n    SOURCE_EXCLUSION = auto()\n    ICON = auto()\n\n\n@unique\nclass IconConfigKey(AutoNameToLower):\n    MODE = auto()\n    PATH = auto()\n    BTRFS_LOGO = \"btrfs-logo\"\n\n\n@unique\nclass BootStanzaIconGenerationMode(AutoNameToLower):\n    DEFAULT = auto()\n    CUSTOM = auto()\n    EMBED_BTRFS_LOGO = auto()\n\n\n@unique\nclass BtrfsLogoConfigKey(AutoNameToLower):\n    VARIANT = auto()\n    SIZE = auto()\n    HORIZONTAL_ALIGNMENT = auto()\n    VERTICAL_ALIGNMENT = auto()\n\n\n@unique\nclass BtrfsLogoVariant(AutoNameToLower):\n    ORIGINAL = auto()\n    INVERTED = auto()\n\n\n@unique\nclass BtrfsLogoSize(AutoNameToLower):\n    SMALL = auto()\n    MEDIUM = auto()\n    LARGE = auto()\n\n\n@unique\nclass BtrfsLogoHorizontalAlignment(AutoNameToLower):\n    LEFT = auto()\n    CENTER = auto()\n    RIGHT = auto()\n\n\n@unique\nclass BtrfsLogoVerticalAlignment(AutoNameToLower):\n    TOP = auto()\n    CENTER = auto()\n    BOTTOM = auto()\n\n\n@unique\nclass LocalDbKey(AutoNameToLower):\n    PACKAGE_CONFIG = auto()\n    REFIND_CONFIGS = auto()\n    PROCESSING_RESULT = auto()\n\n\n@unique\nclass RefindOption(Enum):\n    ADD_BOOT_OPTIONS = \"add_options\"\n    BOOT_OPTIONS = \"options\"\n    DISABLED = \"disabled\"\n    FIRMWARE_BOOTNUM = \"firmware_bootnum\"\n    GRAPHICS = \"graphics\"\n    ICON = \"icon\"\n    INCLUDE = \"include\"\n    INITRD = \"initrd\"\n    LOADER = \"loader\"\n    MENU_ENTRY = \"menuentry\"\n    OS_TYPE = \"ostype\"\n    SUB_MENU_ENTRY = \"submenuentry\"\n    VOLUME = \"volume\"\n\n\n@unique\nclass OSTypeParameter(Enum):\n    MAC_OS = \"MacOS\"\n    LINUX = \"Linux\"\n    ELILO = \"ELILO\"\n    WINDOWS = \"Windows\"\n    XOM = \"XOM\"\n\n\n@unique\nclass GraphicsParameter(AutoNameToLower):\n    ON = auto()\n    OFF = auto()\n\n\n@unique\nclass BootFilePathSource(Enum):\n    BOOT_STANZA = 0\n    SUB_MENU = 1\n\n\n@unique\nclass StateNames(AutoNameToLower):\n    INITIAL = auto()\n    INITIALIZE_BLOCK_DEVICES = auto()\n    INITIALIZE_ROOT_SUBVOLUME = auto()\n    INITIALIZE_MATCHED_BOOT_STANZAS = auto()\n    INITIALIZE_PREPARED_SNAPSHOTS = auto()\n    COMBINE_BOOT_STANZAS_WITH_SNAPSHOTS = auto()\n    PROCESS_CHANGES = auto()\n    FINAL = auto()\n"
  },
  {
    "path": "src/refind_btrfs/common/exceptions.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom more_itertools import first_true\n\nfrom refind_btrfs.common import constants\nfrom refind_btrfs.utility.helpers import checked_cast\n\n\nclass RefindBtrfsError(Exception):\n    def __init__(self, *args: object) -> None:\n        super().__init__(args)\n\n        if args is not None:\n            self._message = checked_cast(\n                str,\n                first_true(\n                    args,\n                    pred=lambda arg: isinstance(arg, str),\n                    default=constants.EMPTY_STR,\n                ),\n            )\n        else:\n            self._message = constants.EMPTY_STR\n\n    def __str__(self) -> str:\n        return f\"{self.error_type_name}: {self.formatted_message}\"\n\n    @property\n    def formatted_message(self) -> str:\n        return self._message\n\n    @property\n    def error_type_name(self) -> str:\n        return type(self).__name__\n\n\nclass PartitionError(RefindBtrfsError):\n    pass\n\n\nclass SubvolumeError(RefindBtrfsError):\n    pass\n\n\nclass SnapshotMountedAsRootError(SubvolumeError):\n    pass\n\n\nclass SnapshotExcludedFromDeletionError(SubvolumeError):\n    pass\n\n\nclass PackageConfigError(RefindBtrfsError):\n    pass\n\n\nclass RefindConfigError(RefindBtrfsError):\n    pass\n\n\nclass RefindSyntaxError(RefindBtrfsError):\n    def __init__(self, line: int, column: int, message: str) -> None:\n        super().__init__(message)\n\n        self._line = line\n        self._column = column\n\n    @property\n    def formatted_message(self) -> str:\n        return (\n            f\"line - {self._line}, column - {self._column}, message - '{self._message}'\"\n        )\n\n\nclass NoChangesDetectedError(RefindBtrfsError):\n    pass\n"
  },
  {
    "path": "src/refind_btrfs/common/package_config.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nfrom functools import cached_property\nfrom pathlib import Path\nfrom typing import Iterable, Iterator, NamedTuple, Optional, Self, Set\nfrom uuid import UUID\n\nfrom refind_btrfs.common import constants\nfrom refind_btrfs.common.abc import BaseConfig\nfrom refind_btrfs.common.enums import (\n    BootStanzaIconGenerationMode,\n    BtrfsLogoHorizontalAlignment,\n    BtrfsLogoSize,\n    BtrfsLogoVariant,\n    BtrfsLogoVerticalAlignment,\n)\nfrom refind_btrfs.device import BlockDevice, Subvolume\nfrom refind_btrfs.utility.helpers import find_all_directories_in, has_items\n\n\nclass SnapshotSearch(NamedTuple):\n    directory: Path\n    is_nested: bool\n    max_depth: int\n\n    def __eq__(self, other: object) -> bool:\n        if self is other:\n            return True\n\n        if isinstance(other, SnapshotSearch):\n            self_directory_resolved = self.directory.resolve()\n            other_directory_resolved = other.directory.resolve()\n\n            return self_directory_resolved == other_directory_resolved\n\n        return False\n\n\nclass SnapshotManipulation(NamedTuple):\n    selection_count: int\n    modify_read_only_flag: bool\n    destination_directory: Path\n    cleanup_exclusion: Set[Subvolume]\n\n\nclass BtrfsLogo(NamedTuple):\n    variant: BtrfsLogoVariant\n    size: BtrfsLogoSize\n    horizontal_alignment: BtrfsLogoHorizontalAlignment\n    vertical_alignment: BtrfsLogoVerticalAlignment\n\n\nclass Icon(NamedTuple):\n    mode: BootStanzaIconGenerationMode\n    path: Path\n    btrfs_logo: BtrfsLogo\n\n\nclass BootStanzaGeneration(NamedTuple):\n    refind_config: str\n    include_paths: bool\n    include_sub_menus: bool\n    source_exclusion: Set[str]\n    icon: Icon\n\n    def with_include_paths(self, boot_device: Optional[BlockDevice]) -> Self:\n        include_paths = self.include_paths\n\n        if include_paths:\n            include_paths = boot_device is None\n\n        return BootStanzaGeneration(\n            self.refind_config,\n            include_paths,\n            self.include_sub_menus,\n            self.source_exclusion,\n            self.icon,\n        )\n\n\nclass PackageConfig(BaseConfig):\n    def __init__(\n        self,\n        esp_uuid: UUID,\n        exit_if_root_is_snapshot: bool,\n        exit_if_no_changes_are_detected: bool,\n        snapshot_searches: Iterable[SnapshotSearch],\n        snapshot_manipulation: SnapshotManipulation,\n        boot_stanza_generation: BootStanzaGeneration,\n    ) -> None:\n        super().__init__(constants.PACKAGE_CONFIG_FILE)\n\n        self._esp_uuid = esp_uuid\n        self._exit_if_root_is_snapshot = exit_if_root_is_snapshot\n        self._exit_if_no_changes_are_detected = exit_if_no_changes_are_detected\n        self._snapshot_searches = list(snapshot_searches)\n        self._snapshot_manipulation = snapshot_manipulation\n        self._boot_stanza_generation = boot_stanza_generation\n\n    def _get_directories_for_watch(self) -> Iterator[Path]:\n        snapshot_searches = self.snapshot_searches\n\n        if has_items(snapshot_searches):\n            for snapshot_search in snapshot_searches:\n                directory = snapshot_search.directory\n                max_depth = snapshot_search.max_depth - 1\n\n                yield from find_all_directories_in(directory, max_depth)\n\n    @property\n    def esp_uuid(self) -> UUID:\n        return self._esp_uuid\n\n    @property\n    def exit_if_root_is_snapshot(self) -> bool:\n        return self._exit_if_root_is_snapshot\n\n    @property\n    def exit_if_no_changes_are_detected(self) -> bool:\n        return self._exit_if_no_changes_are_detected\n\n    @property\n    def snapshot_searches(self) -> list[SnapshotSearch]:\n        return self._snapshot_searches\n\n    @property\n    def snapshot_manipulation(self) -> SnapshotManipulation:\n        return self._snapshot_manipulation\n\n    @property\n    def boot_stanza_generation(self) -> BootStanzaGeneration:\n        return self._boot_stanza_generation\n\n    @cached_property\n    def directories_for_watch(self) -> Set[Path]:\n        return set(self._get_directories_for_watch())\n"
  },
  {
    "path": "src/refind_btrfs/console/__init__.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom .cli_runner import CLIRunner\n"
  },
  {
    "path": "src/refind_btrfs/console/cli_runner.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport os\n\nfrom injector import inject\n\nfrom refind_btrfs.common import constants\nfrom refind_btrfs.common.abc import BaseRunner\nfrom refind_btrfs.common.abc.factories import BaseLoggerFactory\nfrom refind_btrfs.common.exceptions import SnapshotMountedAsRootError\nfrom refind_btrfs.state_management import RefindBtrfsMachine\n\n\nclass CLIRunner(BaseRunner):\n    @inject\n    def __init__(\n        self, logger_factory: BaseLoggerFactory, machine: RefindBtrfsMachine\n    ) -> None:\n        self._logger = logger_factory.logger(__name__)\n        self._machine = machine\n\n    def run(self) -> int:\n        logger = self._logger\n        machine = self._machine\n        exit_code = os.EX_OK\n\n        try:\n            if not machine.run():\n                exit_code = constants.EX_NOT_OK\n        except SnapshotMountedAsRootError as e:\n            logger.warning(e.formatted_message)\n        except KeyboardInterrupt:\n            exit_code = constants.EX_CTRL_C_INTERRUPT\n            logger.warning(constants.MESSAGE_CTRL_C_INTERRUPT)\n\n        return exit_code\n"
  },
  {
    "path": "src/refind_btrfs/data/refind-btrfs",
    "content": "#!/bin/bash\npython -m refind_btrfs --run-mode one-time\n"
  },
  {
    "path": "src/refind_btrfs/data/refind-btrfs.conf-sample",
    "content": "#######################\n## refind-btrfs.conf ##\n#######################\n\n# TOML syntax\n\n# esp_uuid = <string>\n## Explicitly defined ESP's Part-UUID which can be used in case the ESP itself\n## cannot be automatically located on the system (for whatever reason).\n## This option is, by default, defined as an empty UUID which means that it is\n## ignored.\n\nesp_uuid = \"00000000-0000-0000-0000-000000000000\"\n\n# exit_if_root_is_snapshot = <bool>\n## Whether to issue a warning and prematurely exit in case the root partition\n## is already mounted as a snapshot.\n## WARNING: Disabling this option is considered experimental and may result in\n## unstable and/or erroneous behavior.\n\nexit_if_root_is_snapshot = true\n\n# exit_if_no_changes_are_detected = <bool>\n## Whether to issue a warning and prematurely exit in case no changes were\n## detected by comparing the preparation results of the current run with those\n## of the previous run (if it exists).\n## Changes are considered to be detected in case any of the following\n## conditions are satisfied:\n##      • this configuration file was modified\n##      • rEFInd's configuration file (main or included) was modified\n##      • at least one snapshot was found (either for addition or removal)\n## The time of last modification (st_mtime) is used to detect file changes\n## instead of comparing their contents.\n\nexit_if_no_changes_are_detected = true\n\n# [[snapshot-search]]\n## Array of objects used to configure the behavior of searching for snapshots.\n## The directory (or directories) listed in this array (including nested\n## directories, up to \"max_depth\" - 1) are also watched for changes by the\n## background running mode.\n#\n# directory = <string>\n## Directory in which to search for snapshots (absolute filesystem path).\n## WARNING: This directory must not be the same as or nested in the directory\n## defined by the \"destination_dir\" option (shown further below).\n#\n# is_nested = <bool>\n## Whether to search for snapshots nested within another snapshot. Only one\n## level of nesting is supported and a search is performed in the same\n## directory (if it exists) that is, in this context, relative to the found\n## snapshot's root directory instead of the system's root directory. The same\n## maximum search depth is used, as well.\n## Setting this option to \"false\" potentially also means stopping the search\n## prematurely (i.e., before the maximum search depth was ever reached) in\n## those branches in which a snapshot was found.\n#\n# max_depth = <int>\n## Maximum search depth relative to the search directory.\n## WARNING: Defining a large value can seriously impact performance (of both\n## searching for snapshots and watching for directory changes) in case the tree\n## (whose root is the search directory) is sufficiently large (deep and/or\n## wide).\n\n[[snapshot-search]]\ndirectory = \"/.snapshots\"\nis_nested = false\nmax_depth = 2\n\n# [snapshot-manipulation]\n## Object used to configure the behavior of preparatory steps required\n## to enable booting into snapshots as well as deleting those that aren't\n## needed anymore.\n#\n# selection_count = <int> or <string>\n## Number of snapshots (sorted descending by creation time) to include or\n## \"inf\" to always include every currently present snapshot.\n#\n# modify_read_only_flag = <bool>\n## Whether to change the read-only flag of a snapshot instead of creating\n## a new writable snapshot from it. This option has no meaning for those\n## snapshots that are already writable.\n#\n# destination_directory  = <string>\n## Directory in which writable snapshots are to be placed (absolute filesystem\n## path). This option has no meaning in case the \"modify_read_only_flag\" option\n## is set to \"true\". It needn't exist beforehand as it is created in case it\n## doesn't (including its missing parents, if any).\n## WARNING: This directory must not be the same as or nested in an ony of the\n## snapshot search directories.\n#\n# cleanup_exclusion = <array<string>>\n## Array comprised of UUIDs (duplicates are ignored) of previously\n## created writable snapshots that are to be excluded during automatic cleanup.\n## These snapshots will not be deleted and should always appear as part of a\n## generated boot stanza.\n## See the output of \"btrfs subvolume show <snapshot-filesystem-path>\" for\n## the expected format (shown in the \"UUID\" column). Same remark applies here\n## with regards to the \"modify_read_only_flag\" option.\n\n[snapshot-manipulation]\nselection_count = 5\nmodify_read_only_flag = false\ndestination_directory = \"/root/.refind-btrfs\"\ncleanup_exclusion = []\n\n# [boot-stanza-generation]\n## Object used to configure the process of combining the source boot stanza\n## with previously prepared snapshots into a generated boot stanza.\n#\n# refind_config = <string>\n## Name of rEFInd's main configuration file which must reside somewhere on\n## the ESP. This option must not be defined as a path (neither absolute nor\n## relative).\n#\n# include_paths = <bool>\n## Whether to adjust the \"loader\" and \"initrd\" paths found in the source boot\n## stanza. Setting this option to \"true\" while having a separate /boot\n## partition has no meaning and is ignored.\n#\n# include_sub_menus = <bool>\n## Whether to include sub-menus (\"submenuentry\") defined as part of the source\n## boot stanza in the generated boot stanza. If set to \"true\", only those\n## sub-menus which do not override the main stanza's \"loader\" and \"options\"\n## fields and which do not delete (i.e., set it to nothing) its \"initrd\" field\n## are taken into consideration.\n## WARNING: Enabling this option in combination with setting a large\n## \"selection_count\" value (greater than 10, for example) or, worse yet, by\n## setting it to \"inf\" can potentially result in an overcrowded \"Boot Options\"\n## menu.\n#\n## source_exclusion = <array<string>>\n## Array comprised of loader filenames (\"loader\") with which the matched source\n## boot stanzas can be arbitrarily excluded from processing, i.e., these boot\n## stanzas will not be taken into account during the generation phase.\n## For example, it can be defined as: [\"vmlinuz-linux\", \"vmlinuz-linux-lts\"].\n## WARNING: This array must not contain all of the matched source boot stanza's\n## loader filenames. If it does, an error is issued and a premature exit is\n## performed.\n## Also, a manual cleanup of the generated boot stanza (or stanzas) and its\n## inclusion within the rEFInd's main configuration file is required in case\n## the array's members were defined after the fact.\n\n[boot-stanza-generation]\nrefind_config = \"refind.conf\"\ninclude_paths = true\ninclude_sub_menus = false\nsource_exclusion = []\n\n# [boot-stanza-generation.icon]\n## Subobject used to configure the process of defining the generated boot\n## stanza's icon.\n#\n# mode = <string>\n## Selected mode of icon generation which can be defined as one of:\n##      • \"default\" - the source boot stanza's icon is reused, as is\n##      • \"custom\" - a user provided image file path is used as the icon\n##      • \"embed_btrfs_logo\" - the Btrfs logo is embedded into the source boot\n##                             stanza's icon\n#\n## path = <string>\n## Path of the user provided image file, relative to whichever directory the\n## file defined by the \"refind_config\" option was found. This option is taken\n## into consideration in case the \"mode\" option is set to \"custom\" but is\n## otherwise ignored.\n## WARNING: The format of the image located at this path must be one of those\n## which rEFInd itself supports, that is one of the following: PNG, JPEG, BMP\n## or ICNS.\n\n[boot-stanza-generation.icon]\nmode = \"default\"\npath = \"btrfs-snapshot-stanzas/icons/sample_icon.png\"\n\n# [boot-stanza-generation.icon.btrfs-logo]\n## Subobject used to configure the behavior of embedding the Btrfs logo into\n## the source boot stanza's icon. It is taken into consideration in case the\n## \"mode\" option is set to \"embed_btrfs_logo\" but is otherwise ignored.\n## WARNING: The source boot stanza icon's format must be PNG and its dimensions\n## (width or height) must exceed those defined by the \"size\" option.\n#\n# variant = <string>\n## Btrfs logo variant to be used for embedding which can be defined as one of:\n##      • \"original\" - dark variant, suitable for light themes (including the\n##                     default theme)\n##      • \"inverted\" - light variant created by inverting the original logo's\n##                     pixels' color values, suitable for dark themes\n#\n# size = <string>\n## Size of the chosen Btrfs logo's variant defined by the \"type\" option. Both\n## variants come in three different sizes which should be a sufficiently\n## flexible choice and as such suitable for a decent number of different OS\n## icons, both default and custom. It can be defined as one of:\n##      • \"small\" - 32x20 pixels\n##      • \"medium\" - 48x30 pixels\n##      • \"large\" - 64x40 pixels\n#\n# horizontal_alignment = <string>\n## Horizontal alignment (x-axis) of the embedded Btrfs logo which can be\n## defined as one of:\n##      • \"left\"\n##      • \"center\"\n##      • \"right\"\n#\n# vertical_alignment = <string>\n## Vertical alignment (y-axis) of the embedded Btrfs logo which can be defined\n## as one of:\n##      • \"top\"\n##      • \"center\"\n##      • \"bottom\"\n\n[boot-stanza-generation.icon.btrfs-logo]\nvariant = \"original\"\nsize = \"medium\"\nhorizontal_alignment = \"center\"\nvertical_alignment = \"center\"\n"
  },
  {
    "path": "src/refind_btrfs/data/refind-btrfs.service",
    "content": "[Unit]\nDescription=Generate rEFInd manual boot stanzas from Btrfs snapshots\nAfter=multi-user.target\nBefore=snapper-boot.service\n\n[Service]\nType=notify\nNotifyAccess=main\nKillMode=mixed\nKillSignal=SIGTERM\nRestartKillSignal=SIGTERM\nExecStart=/usr/bin/python -m refind_btrfs --run-mode background\n\n[Install]\nWantedBy=multi-user.target\n"
  },
  {
    "path": "src/refind_btrfs/device/__init__.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom .block_device import BlockDevice\nfrom .filesystem import Filesystem\nfrom .mount_options import MountOptions\nfrom .partition import Partition\nfrom .partition_table import PartitionTable\nfrom .subvolume import NumIdRelation, Subvolume, UuidRelation\n"
  },
  {
    "path": "src/refind_btrfs/device/block_device.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nimport re\nfrom typing import Iterable, Optional, Self, Union\n\nfrom refind_btrfs.common.abc.factories import BaseDeviceCommandFactory\nfrom refind_btrfs.utility.helpers import has_items, none_throws\n\nfrom .partition import Partition\nfrom .partition_table import PartitionTable\n\n\nclass BlockDevice:\n    def __init__(self, name: str, d_type: str, major_minor: str) -> None:\n        self._name = name\n        self._d_type = d_type\n\n        major_minor_parsed = BlockDevice.try_parse_major_minor(major_minor)\n\n        self._major_number = major_minor_parsed[0]\n        self._minor_number = major_minor_parsed[1]\n        self._physical_partition_table: Optional[PartitionTable] = None\n        self._live_partition_table: Optional[PartitionTable] = None\n        self._dependencies: Optional[list[BlockDevice]] = None\n\n    def with_dependencies(self, dependencies: Iterable[BlockDevice]) -> Self:\n        self._dependencies = list(dependencies)\n\n        return self\n\n    def initialize_partition_tables_using(\n        self,\n        device_command_factory: BaseDeviceCommandFactory,\n    ) -> None:\n        if not self.has_physical_partition_table():\n            physical_device_command = device_command_factory.physical_device_command()\n\n            self._physical_partition_table = (\n                physical_device_command.get_partition_table_for(self)\n            )\n\n        if not self.has_live_partition_table():\n            live_device_command = device_command_factory.live_device_command()\n\n            self._live_partition_table = live_device_command.get_partition_table_for(\n                self\n            )\n\n    def is_matched_with(self, name: str) -> bool:\n        if self.name == name:\n            return True\n        else:\n            dependencies = self.dependencies\n\n            if has_items(dependencies):\n                return any(\n                    dependency.is_matched_with(name)\n                    for dependency in none_throws(dependencies)\n                )\n\n        return False\n\n    def has_physical_partition_table(self) -> bool:\n        return self.physical_partition_table is not None\n\n    def has_live_partition_table(self) -> bool:\n        return self.live_partition_table is not None\n\n    def has_esp(self) -> bool:\n        return self.esp is not None\n\n    def has_root(self) -> bool:\n        return self.root is not None\n\n    def has_boot(self) -> bool:\n        return self.boot is not None\n\n    @staticmethod\n    def try_parse_major_minor(value: str) -> Union[list[int], list[None]]:\n        match = re.fullmatch(r\"\\d+:\\d+\", value)\n\n        if match:\n            return [int(split_number) for split_number in match.group().split(\":\")]\n\n        return [None, None]\n\n    @property\n    def name(self) -> str:\n        return self._name\n\n    @property\n    def d_type(self) -> str:\n        return self._d_type\n\n    @property\n    def major_number(self) -> Optional[int]:\n        return self._major_number\n\n    @property\n    def minor_number(self) -> Optional[int]:\n        return self._minor_number\n\n    @property\n    def physical_partition_table(\n        self,\n    ) -> Optional[PartitionTable]:\n        return self._physical_partition_table\n\n    @property\n    def live_partition_table(\n        self,\n    ) -> Optional[PartitionTable]:\n        return self._live_partition_table\n\n    @property\n    def dependencies(self) -> Optional[list[BlockDevice]]:\n        return self._dependencies\n\n    @property\n    def esp(self) -> Optional[Partition]:\n        if self.has_physical_partition_table():\n            return none_throws(self.physical_partition_table).esp\n\n        return None\n\n    @property\n    def root(self) -> Optional[Partition]:\n        if self.has_live_partition_table():\n            return none_throws(self.live_partition_table).root\n\n        return None\n\n    @property\n    def boot(self) -> Optional[Partition]:\n        if self.has_live_partition_table():\n            return none_throws(self.live_partition_table).boot\n\n        return None\n"
  },
  {
    "path": "src/refind_btrfs/device/filesystem.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nfrom pathlib import Path\nfrom typing import Optional, Self\n\nfrom refind_btrfs.common.abc.factories import BaseSubvolumeCommandFactory\nfrom refind_btrfs.utility.helpers import is_none_or_whitespace\n\nfrom .mount_options import MountOptions\nfrom .subvolume import Subvolume\n\n\nclass Filesystem:\n    def __init__(self, uuid: str, label: str, fs_type: str, mount_point: str) -> None:\n        self._uuid = uuid\n        self._label = label\n        self._fs_type = fs_type\n        self._mount_point = mount_point\n        self._dump: Optional[int] = None\n        self._fsck: Optional[int] = None\n        self._mount_options: Optional[MountOptions] = None\n        self._subvolume: Optional[Subvolume] = None\n\n    def with_dump_and_fsck(self, dump: int, fsck: int) -> Self:\n        self._dump = dump\n        self._fsck = fsck\n\n        return self\n\n    def with_mount_options(self, raw_mount_options: str) -> Self:\n        self._mount_options = (\n            MountOptions(raw_mount_options)\n            if not is_none_or_whitespace(raw_mount_options)\n            else None\n        )\n\n        return self\n\n    def initialize_subvolume_using(\n        self, subvolume_command_factory: BaseSubvolumeCommandFactory\n    ) -> None:\n        if not self.has_subvolume():\n            filesystem_path = Path(self.mount_point)\n            subvolume_command = subvolume_command_factory.subvolume_command()\n            subvolume = subvolume_command.get_subvolume_from(filesystem_path)\n\n            if subvolume is not None:\n                snapshots = subvolume_command.get_all_source_snapshots_for(subvolume)\n\n                self._subvolume = subvolume.with_snapshots(snapshots)\n\n    def is_of_type(self, fs_type: str) -> bool:\n        return self.fs_type == fs_type\n\n    def is_mounted(self) -> bool:\n        return not is_none_or_whitespace(self.mount_point)\n\n    def is_mounted_at(self, path: Path) -> bool:\n        return self.is_mounted() and Path(self.mount_point) == path\n\n    def has_subvolume(self) -> bool:\n        return self.subvolume is not None\n\n    @property\n    def uuid(self) -> str:\n        return self._uuid\n\n    @property\n    def label(self) -> str:\n        return self._label\n\n    @property\n    def fs_type(self) -> str:\n        return self._fs_type\n\n    @property\n    def mount_point(self) -> str:\n        return self._mount_point\n\n    @property\n    def dump(self) -> Optional[int]:\n        return self._dump\n\n    @property\n    def fsck(self) -> Optional[int]:\n        return self._fsck\n\n    @property\n    def mount_options(self) -> Optional[MountOptions]:\n        return self._mount_options\n\n    @property\n    def subvolume(self) -> Optional[Subvolume]:\n        return self._subvolume\n"
  },
  {
    "path": "src/refind_btrfs/device/mount_options.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport re\n\nfrom refind_btrfs.common import constants\nfrom refind_btrfs.common.exceptions import PartitionError\nfrom refind_btrfs.utility.helpers import (\n    checked_cast,\n    has_items,\n    is_none_or_whitespace,\n    try_parse_int,\n)\n\nfrom .subvolume import Subvolume\n\n\nclass MountOptions:\n    def __init__(self, raw_mount_options: str) -> None:\n        split_mount_options = [\n            option.strip()\n            for option in raw_mount_options.split(constants.COLUMN_SEPARATOR)\n        ]\n        simple_options: list[tuple[int, str]] = []\n        parameterized_options: dict[str, tuple[int, str]] = {}\n        parameterized_option_prefix_pattern = re.compile(\n            constants.PARAMETERIZED_OPTION_PREFIX_PATTERN\n        )\n\n        for position, option in enumerate(split_mount_options):\n            if not is_none_or_whitespace(option):\n                if parameterized_option_prefix_pattern.match(option):\n                    split_parameterized_option = option.split(\n                        constants.PARAMETERIZED_OPTION_SEPARATOR\n                    )\n                    option_name = checked_cast(str, split_parameterized_option[0])\n                    option_value = checked_cast(str, split_parameterized_option[1])\n\n                    if option_name in parameterized_options:\n                        raise PartitionError(\n                            f\"The '{option_name}' mount option \"\n                            f\"cannot be defined multiple times!\"\n                        )\n\n                    parameterized_options[option_name] = (position, option_value)\n                else:\n                    simple_options.append((position, option))\n\n        self._simple_options = simple_options\n        self._parameterized_options = parameterized_options\n\n    def __str__(self) -> str:\n        simple_options = self._simple_options\n        parameterized_options = self._parameterized_options\n        result: list[str] = [constants.EMPTY_STR] * sum(\n            (len(simple_options), len(parameterized_options))\n        )\n\n        if has_items(simple_options):\n            for simple_option in simple_options:\n                result[simple_option[0]] = simple_option[1]\n\n        if has_items(parameterized_options):\n            for option_name, option_value in parameterized_options.items():\n                result[option_value[0]] = constants.PARAMETERIZED_OPTION_SEPARATOR.join(\n                    (option_name, option_value[1])\n                )\n\n        if has_items(result):\n            return constants.COLUMN_SEPARATOR.join(result)\n\n        return constants.EMPTY_STR\n\n    def is_matched_with(self, subvolume: Subvolume) -> bool:\n        parameterized_options = self._parameterized_options\n        subvol_tuple = parameterized_options.get(constants.SUBVOL_OPTION)\n        subvolid_tuple = parameterized_options.get(constants.SUBVOLID_OPTION)\n        subvol_matched = False\n        subvolid_matched = False\n\n        if subvol_tuple is not None:\n            subvol_value = subvol_tuple[1]\n            logical_path = subvolume.logical_path\n            subvol_prefix_pattern = re.compile(f\"^{constants.DIR_SEPARATOR_PATTERN}\")\n\n            subvol_matched = subvol_prefix_pattern.sub(\n                constants.EMPTY_STR, subvol_value\n            ) == subvol_prefix_pattern.sub(constants.EMPTY_STR, logical_path)\n\n        if subvolid_tuple is not None:\n            subvolid_value = subvolid_tuple[1]\n            num_id = subvolume.num_id\n\n            subvolid_matched = try_parse_int(subvolid_value) == num_id\n\n        return subvol_matched or subvolid_matched\n\n    def migrate_from_to(\n        self, source_subvolume: Subvolume, destination_subvolume: Subvolume\n    ) -> None:\n        if not self.is_matched_with(source_subvolume):\n            raise PartitionError(\n                \"The mount options are not matched with the \"\n                \"'source_subvolume' parameter (by 'subvol' or 'subvolid')!\"\n            )\n\n        parameterized_options = self._parameterized_options\n        subvol_tuple = parameterized_options.get(constants.SUBVOL_OPTION)\n        subvolid_tuple = parameterized_options.get(constants.SUBVOLID_OPTION)\n\n        if subvol_tuple is not None:\n            subvol_value = subvol_tuple[1]\n            source_logical_path = source_subvolume.logical_path\n            destination_logical_path = destination_subvolume.logical_path\n            subvol_pattern = re.compile(\n                rf\"(?P<prefix>^{constants.DIR_SEPARATOR_PATTERN}?){source_logical_path}$\"\n            )\n\n            parameterized_options[constants.SUBVOL_OPTION] = (\n                subvol_tuple[0],\n                subvol_pattern.sub(\n                    rf\"\\g<prefix>{destination_logical_path}\", subvol_value\n                ),\n            )\n\n        if subvolid_tuple is not None:\n            num_id = destination_subvolume.num_id\n\n            parameterized_options[constants.SUBVOLID_OPTION] = (\n                subvolid_tuple[0],\n                str(num_id),\n            )\n\n    @property\n    def simple_options(self) -> list[str]:\n        return [simple_option[1] for simple_option in self._simple_options]\n\n    @property\n    def parameterized_options(self) -> dict[str, str]:\n        return {\n            option_name: option_value[1]\n            for option_name, option_value in self._parameterized_options.items()\n        }\n"
  },
  {
    "path": "src/refind_btrfs/device/partition.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nfrom pathlib import Path\nfrom typing import Optional, Self\nfrom uuid import UUID\n\nfrom refind_btrfs.common import constants\nfrom refind_btrfs.utility.helpers import (\n    find_all_matched_files_in,\n    is_none_or_whitespace,\n    none_throws,\n    try_parse_int,\n    try_parse_uuid,\n)\n\nfrom .filesystem import Filesystem\n\n\nclass Partition:\n    def __init__(self, uuid: str, name: str, label: str) -> None:\n        self._uuid = uuid\n        self._name = name\n        self._label = label\n        self._part_type_code: Optional[int] = None\n        self._part_type_uuid: Optional[UUID] = None\n        self._filesystem: Optional[Filesystem] = None\n\n    def __eq__(self, other: object) -> bool:\n        if self is other:\n            return True\n\n        if isinstance(other, Partition):\n            return self.uuid == other.uuid\n\n        return False\n\n    def __hash__(self) -> int:\n        return hash(self.uuid)\n\n    def with_part_type(self, part_type: str) -> Self:\n        self._part_type_code = try_parse_int(part_type, base=16)\n        self._part_type_uuid = try_parse_uuid(part_type)\n\n        return self\n\n    def with_filesystem(self, filesystem: Filesystem) -> Self:\n        self._filesystem = filesystem\n\n        return self\n\n    def is_esp(self, uuid: UUID) -> bool:\n        filesystem = self.filesystem\n\n        if filesystem is not None:\n            if uuid == constants.EMPTY_UUID:\n                is_matched = (\n                    self.part_type_code == constants.ESP_PART_TYPE_CODE\n                    or self.part_type_uuid == constants.ESP_PART_TYPE_UUID\n                )\n            else:\n                parsed_uuid = try_parse_uuid(self.uuid)\n\n                is_matched = uuid == parsed_uuid\n\n            return (\n                is_matched\n                and filesystem.is_mounted()\n                and filesystem.is_of_type(constants.ESP_FS_TYPE)\n            )\n\n        return False\n\n    def is_root(self) -> bool:\n        filesystem = self.filesystem\n\n        if filesystem is not None:\n            directory = constants.ROOT_DIR\n\n            return filesystem.is_mounted_at(directory)\n\n        return False\n\n    def is_boot(self) -> bool:\n        filesystem = self.filesystem\n\n        if filesystem is not None:\n            directory = constants.ROOT_DIR / constants.BOOT_DIR\n\n            return filesystem.is_mounted_at(directory)\n\n        return False\n\n    def search_paths_for(self, filename: str) -> Optional[list[Path]]:\n        if is_none_or_whitespace(filename):\n            raise ValueError(\"The 'filename' parameter must be initialized!\")\n\n        filesystem = none_throws(self.filesystem)\n\n        if filesystem.is_mounted():\n            search_directory = Path(filesystem.mount_point)\n            all_matches = find_all_matched_files_in(search_directory, filename)\n\n            return list(all_matches)\n\n        return None\n\n    @property\n    def uuid(self) -> str:\n        return self._uuid\n\n    @property\n    def name(self) -> str:\n        return self._name\n\n    @property\n    def label(self) -> str:\n        return self._label\n\n    @property\n    def part_type_code(self) -> Optional[int]:\n        return self._part_type_code\n\n    @property\n    def part_type_uuid(self) -> Optional[UUID]:\n        return self._part_type_uuid\n\n    @property\n    def filesystem(self) -> Optional[Filesystem]:\n        return self._filesystem\n"
  },
  {
    "path": "src/refind_btrfs/device/partition_table.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nimport re\nfrom functools import cached_property\nfrom pathlib import Path\nfrom typing import Iterable, Optional, Self\nfrom uuid import UUID\n\nfrom more_itertools import only, take\n\nfrom refind_btrfs.common import constants\nfrom refind_btrfs.common.enums import FstabColumn\nfrom refind_btrfs.utility.helpers import has_items, is_none_or_whitespace, none_throws\n\nfrom .partition import Partition\nfrom .subvolume import Subvolume\n\n\nclass PartitionTable:\n    def __init__(self, uuid: str, pt_type: str) -> None:\n        self._uuid = uuid\n        self._pt_type = pt_type\n        self._esp_uuid = constants.EMPTY_UUID\n        self._fstab_file_path: Optional[Path] = None\n        self._partitions: Optional[list[Partition]] = None\n\n    def __eq__(self, other: object) -> bool:\n        if self is other:\n            return True\n\n        if isinstance(other, PartitionTable):\n            return self.uuid == other.uuid\n\n        return False\n\n    def __hash__(self) -> int:\n        return hash(self.uuid)\n\n    def with_esp_uuid(self, esp_uuid: UUID) -> Self:\n        self._esp_uuid = esp_uuid\n\n        return self\n\n    def with_fstab_file_path(self, fstab_file_path: Path) -> Self:\n        self._fstab_file_path = fstab_file_path\n\n        return self\n\n    def with_partitions(self, partitions: Iterable[Partition]) -> Self:\n        self._partitions = list(partitions)\n\n        return self\n\n    def is_matched_with(self, subvolume: Subvolume) -> bool:\n        root = self.root\n\n        if root is not None:\n            filesystem = none_throws(root.filesystem)\n            mount_options = none_throws(filesystem.mount_options)\n\n            return mount_options.is_matched_with(subvolume)\n\n        return False\n\n    def has_partitions(self) -> bool:\n        return has_items(self.partitions)\n\n    def migrate_from_to(\n        self, source_subvolume: Subvolume, destination_subvolume: Subvolume\n    ) -> None:\n        root = none_throws(self.root)\n        filesystem = none_throws(root.filesystem)\n        mount_options = none_throws(filesystem.mount_options)\n        destination_filesystem_path = destination_subvolume.filesystem_path\n\n        mount_options.migrate_from_to(source_subvolume, destination_subvolume)\n\n        self._fstab_file_path = destination_filesystem_path / constants.FSTAB_FILE\n\n    def transform_fstab_line(self, fstab_line: str) -> str:\n        if PartitionTable.is_valid_fstab_entry(fstab_line):\n            root = none_throws(self.root)\n            filesystem = none_throws(root.filesystem)\n            root_mount_point = filesystem.mount_point\n            split_fstab_entry = fstab_line.split()\n            fstab_mount_point = split_fstab_entry[FstabColumn.FS_MOUNT_POINT.value]\n\n            if root_mount_point == fstab_mount_point:\n                fstab_mount_options = split_fstab_entry[\n                    FstabColumn.FS_MOUNT_OPTIONS.value\n                ]\n                pattern = re.compile(\n                    r\"(?P<whitespace_before>\\s+)\"\n                    f\"{fstab_mount_options}\"\n                    r\"(?P<whitespace_after>\\s+)\"\n                )\n                root_mount_options = str(filesystem.mount_options)\n\n                return pattern.sub(\n                    r\"\\g<whitespace_before>\"\n                    f\"{root_mount_options}\"\n                    r\"\\g<whitespace_after>\",\n                    fstab_line,\n                )\n\n        return fstab_line\n\n    @staticmethod\n    def is_valid_fstab_entry(value: Optional[str]) -> bool:\n        if is_none_or_whitespace(value):\n            return False\n\n        fstab_line = none_throws(value)\n        comment_pattern = re.compile(r\"^\\s*#.*\")\n\n        if not comment_pattern.match(fstab_line):\n            columns_count = len(FstabColumn)\n            split_fstab_entry = take(columns_count, fstab_line.split())\n\n            return (\n                has_items(split_fstab_entry) and len(split_fstab_entry) == columns_count\n            )\n\n        return False\n\n    @property\n    def uuid(self) -> str:\n        return self._uuid\n\n    @property\n    def pt_type(self) -> str:\n        return self._pt_type\n\n    @property\n    def esp_uuid(self) -> UUID:\n        return self._esp_uuid\n\n    @property\n    def fstab_file_path(self) -> Optional[Path]:\n        return self._fstab_file_path\n\n    @property\n    def partitions(self) -> Optional[list[Partition]]:\n        return self._partitions\n\n    @cached_property\n    def esp(self) -> Optional[Partition]:\n        if self.has_partitions():\n            return only(\n                partition\n                for partition in none_throws(self.partitions)\n                if partition.is_esp(self.esp_uuid)\n            )\n\n        return None\n\n    @cached_property\n    def root(self) -> Optional[Partition]:\n        if self.has_partitions():\n            return only(\n                partition\n                for partition in none_throws(self.partitions)\n                if partition.is_root()\n            )\n\n        return None\n\n    @cached_property\n    def boot(self) -> Optional[Partition]:\n        if self.has_partitions():\n            return only(\n                partition\n                for partition in none_throws(self.partitions)\n                if partition.is_boot()\n            )\n\n        return None\n"
  },
  {
    "path": "src/refind_btrfs/device/subvolume.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nfrom copy import deepcopy\nfrom datetime import datetime\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Iterable, NamedTuple, Optional, Self, Set\nfrom uuid import UUID\n\nfrom more_itertools import take\n\nfrom refind_btrfs.common import BootFilesCheckResult, constants\nfrom refind_btrfs.common.abc.factories import BaseDeviceCommandFactory\nfrom refind_btrfs.common.enums import PathRelation\nfrom refind_btrfs.common.exceptions import SubvolumeError\nfrom refind_btrfs.utility.helpers import (\n    discern_path_relation_of,\n    has_items,\n    is_none_or_whitespace,\n    none_throws,\n    replace_root_part_in,\n)\n\nif TYPE_CHECKING:\n    from refind_btrfs.boot import BootStanza\n\n    from .partition_table import PartitionTable\n\n\nclass NumIdRelation(NamedTuple):\n    self_id: int\n    parent_id: int\n\n\nclass UuidRelation(NamedTuple):\n    self_uuid: UUID\n    parent_uuid: UUID\n\n\nclass Subvolume:\n    def __init__(\n        self,\n        filesystem_path: Path,\n        logical_path: str,\n        time_created: datetime,\n        uuid_relation: UuidRelation,\n        num_id_relation: NumIdRelation,\n        is_read_only: bool,\n    ) -> None:\n        self._name: Optional[str] = None\n        self._filesystem_path = filesystem_path\n        self._logical_path = logical_path\n        self._time_created = time_created\n        self._uuid = uuid_relation.self_uuid\n        self._parent_uuid = uuid_relation.parent_uuid\n        self._num_id = num_id_relation.self_id\n        self._parent_num_id = num_id_relation.parent_id\n        self._is_read_only = is_read_only\n        self._created_from: Optional[Subvolume] = None\n        self._static_partition_table: Optional[PartitionTable] = None\n        self._boot_files_check_result: Optional[BootFilesCheckResult] = None\n        self._snapshots: Optional[Set[Subvolume]] = None\n\n    def __eq__(self, other: object) -> bool:\n        if self is other:\n            return True\n\n        if isinstance(other, Subvolume):\n            return self.uuid == other.uuid\n\n        return False\n\n    def __hash__(self) -> int:\n        return hash(self.uuid)\n\n    def __lt__(self, other: object) -> bool:\n        if isinstance(other, Subvolume):\n            attributes_for_comparison = [\n                none_throws(subvolume.created_from).time_created\n                if subvolume.is_newly_created()\n                else subvolume.time_created\n                for subvolume in (self, other)\n            ]\n\n            return attributes_for_comparison[0] < attributes_for_comparison[1]\n\n        return False\n\n    def with_boot_files_check_result(self, boot_stanza: BootStanza) -> Self:\n        boot_stanza_check_result = boot_stanza.boot_files_check_result\n\n        if boot_stanza_check_result is not None:\n            self_filesystem_path_str = str(self.filesystem_path)\n            self_logical_path = self.logical_path\n            boot_stanza_name = boot_stanza_check_result.required_by_boot_stanza_name\n            expected_logical_path = boot_stanza_check_result.expected_logical_path\n            required_file_paths = boot_stanza_check_result.matched_boot_files\n            matched_boot_files: list[str] = []\n            unmatched_boot_files: list[str] = []\n\n            for file_path in required_file_paths:\n                replaced_file_path = Path(\n                    replace_root_part_in(\n                        file_path, expected_logical_path, self_filesystem_path_str\n                    )\n                )\n                append_func = (\n                    matched_boot_files.append\n                    if replaced_file_path.exists()\n                    else unmatched_boot_files.append\n                )\n\n                append_func(replaced_file_path.name)\n\n            self._boot_files_check_result = BootFilesCheckResult(\n                boot_stanza_name,\n                self_logical_path,\n                matched_boot_files,\n                unmatched_boot_files,\n            )\n\n        return self\n\n    def with_snapshots(self, snapshots: Iterable[Subvolume]) -> Self:\n        self._snapshots = set(snapshots)\n\n        return self\n\n    def as_named(self) -> Self:\n        type_prefix = \"ro\" if self.is_read_only else \"rw\"\n        type_prefix += \"snap\" if self.is_snapshot() else \"subvol\"\n\n        if self.is_newly_created():\n            created_from = none_throws(self.created_from)\n            time_created = created_from.time_created\n            num_id = created_from.num_id\n        else:\n            time_created = self.time_created\n            num_id = self.num_id\n\n        formatted_time_created = time_created.strftime(\"%Y-%m-%d_%H-%M-%S\")\n\n        self._name = f\"{type_prefix}_{formatted_time_created}_ID{num_id}\"\n\n        return self\n\n    def as_located_in(self, parent_directory: Path) -> Self:\n        if not self.is_named():\n            raise ValueError(\"The '_name' attribute must be initialized!\")\n\n        name = none_throws(self.name)\n\n        self._filesystem_path = parent_directory / name\n\n        return self\n\n    def as_writable(self) -> Self:\n        self._is_read_only = False\n\n        return self\n\n    def as_newly_created_from(self, other: Subvolume) -> Self:\n        self._created_from = other\n\n        if other.has_static_partition_table():\n            self._static_partition_table = deepcopy(\n                none_throws(other.static_partition_table)\n            )\n\n        return self\n\n    def to_destination(self, directory: Path) -> Self:\n        return (\n            Subvolume(\n                constants.EMPTY_PATH,\n                constants.EMPTY_STR,\n                datetime.min,\n                UuidRelation(constants.EMPTY_UUID, self.uuid),\n                NumIdRelation(0, self.num_id),\n                False,\n            )\n            .as_newly_created_from(self)\n            .as_named()\n            .as_located_in(directory)\n        )\n\n    def initialize_partition_table_using(\n        self, device_command_factory: BaseDeviceCommandFactory\n    ) -> None:\n        if not self.has_static_partition_table():\n            static_device_command = device_command_factory.static_device_command()\n\n            self._static_partition_table = (\n                static_device_command.get_partition_table_for(self)\n            )\n\n    def is_named(self) -> bool:\n        return not is_none_or_whitespace(self.name)\n\n    def is_snapshot(self) -> bool:\n        return self.parent_uuid != constants.EMPTY_UUID\n\n    def is_snapshot_of(self, subvolume: Subvolume) -> bool:\n        return self.is_snapshot() and self.parent_uuid == subvolume.uuid\n\n    def is_located_in(self, parent_directory: Path) -> bool:\n        if self.is_newly_created():\n            created_from = none_throws(self.created_from)\n            filesystem_path = created_from.filesystem_path\n        else:\n            filesystem_path = self.filesystem_path\n\n        path_relation = discern_path_relation_of((parent_directory, filesystem_path))\n        expected_results: list[PathRelation] = [\n            PathRelation.SAME,\n            PathRelation.SECOND_NESTED_IN_FIRST,\n        ]\n\n        return path_relation in expected_results\n\n    def is_newly_created(self) -> bool:\n        return self.created_from is not None\n\n    def is_static_partition_table_matched_with(self, subvolume: Subvolume) -> bool:\n        if self.has_static_partition_table():\n            static_partition_table = none_throws(self.static_partition_table)\n\n            return static_partition_table.is_matched_with(subvolume)\n\n        return False\n\n    def has_static_partition_table(self) -> bool:\n        return self.static_partition_table is not None\n\n    def has_unmatched_boot_files(self) -> bool:\n        boot_files_check_result = self.boot_files_check_result\n\n        if boot_files_check_result is not None:\n            return boot_files_check_result.has_unmatched_boot_files()\n\n        return False\n\n    def has_snapshots(self) -> bool:\n        return has_items(self.snapshots)\n\n    def can_be_added(self, comparison_iterable: Iterable[Subvolume]) -> bool:\n        if self not in comparison_iterable:\n            return not any(\n                subvolume.is_newly_created() and subvolume.is_snapshot_of(self)\n                for subvolume in comparison_iterable\n            )\n\n        return False\n\n    def can_be_removed(\n        self, parent_directory: Path, comparison_iterable: Iterable[Subvolume]\n    ) -> bool:\n        if self not in comparison_iterable:\n            if self.is_newly_created() or self.is_located_in(parent_directory):\n                return not any(\n                    self.is_snapshot_of(subvolume) for subvolume in comparison_iterable\n                )\n\n            return True\n\n        return False\n\n    def select_snapshots(self, count: int) -> Optional[list[Subvolume]]:\n        if self.has_snapshots():\n            snapshots = none_throws(self.snapshots)\n\n            return take(count, sorted(snapshots, reverse=True))\n\n        return None\n\n    def modify_partition_table_using(\n        self,\n        source_subvolume: Subvolume,\n        device_command_factory: BaseDeviceCommandFactory,\n    ) -> None:\n        self.initialize_partition_table_using(device_command_factory)\n\n        static_partition_table = none_throws(self.static_partition_table)\n\n        if not static_partition_table.is_matched_with(self):\n            static_device_command = device_command_factory.static_device_command()\n\n            static_partition_table.migrate_from_to(source_subvolume, self)\n            static_device_command.save_partition_table(static_partition_table)\n\n    def validate_static_partition_table(self, subvolume: Subvolume) -> None:\n        logical_path = self.logical_path\n\n        if not self.has_static_partition_table():\n            raise SubvolumeError(\n                f\"The '{logical_path}' subvolume's static \"\n                \"partition table is not initialized!\"\n            )\n\n        static_partition_table = none_throws(self.static_partition_table)\n        root = static_partition_table.root\n\n        if root is None:\n            raise SubvolumeError(\n                f\"Could not find the root partition in the '{logical_path}' \"\n                \"subvolume's static partition table!\"\n            )\n\n        if not static_partition_table.is_matched_with(subvolume):\n            raise SubvolumeError(\n                f\"The '{logical_path}' subvolume's static partition table is not \"\n                \"matched with the root subvolume (by 'subvol' or 'subvolid')!\"\n            )\n\n    def validate_boot_files_check_result(self) -> None:\n        if self.has_unmatched_boot_files():\n            boot_files_check_result = none_throws(self.boot_files_check_result)\n            boot_stanza_name = boot_files_check_result.required_by_boot_stanza_name\n            logical_path = boot_files_check_result.expected_logical_path\n            unmatched_boot_files = boot_files_check_result.unmatched_boot_files\n\n            raise SubvolumeError(\n                f\"Detected boot files required by the '{boot_stanza_name}' boot \"\n                f\"stanza which do not exist in the '{logical_path}' subvolume: \"\n                f\"{constants.DEFAULT_ITEMS_SEPARATOR.join(unmatched_boot_files)}!\"\n            )\n\n    @property\n    def name(self) -> Optional[str]:\n        return self._name\n\n    @property\n    def filesystem_path(self) -> Path:\n        return self._filesystem_path\n\n    @property\n    def logical_path(self) -> str:\n        return self._logical_path\n\n    @property\n    def time_created(self) -> datetime:\n        return self._time_created\n\n    @property\n    def uuid(self) -> UUID:\n        return self._uuid\n\n    @property\n    def parent_uuid(self) -> UUID:\n        return self._parent_uuid\n\n    @property\n    def num_id(self) -> int:\n        return self._num_id\n\n    @property\n    def parent_num_id(self) -> int:\n        return self._parent_num_id\n\n    @property\n    def is_read_only(self) -> bool:\n        return self._is_read_only\n\n    @property\n    def created_from(self) -> Optional[Subvolume]:\n        return self._created_from\n\n    @property\n    def static_partition_table(self) -> Optional[PartitionTable]:\n        return self._static_partition_table\n\n    @property\n    def boot_files_check_result(self) -> Optional[BootFilesCheckResult]:\n        return self._boot_files_check_result\n\n    @property\n    def snapshots(self) -> Optional[Set[Subvolume]]:\n        return self._snapshots\n"
  },
  {
    "path": "src/refind_btrfs/service/__init__.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom .snapshot_event_handler import SnapshotEventHandler\nfrom .snapshot_observer import SnapshotObserver\nfrom .watchdog_runner import WatchdogRunner\n"
  },
  {
    "path": "src/refind_btrfs/service/snapshot_event_handler.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom pathlib import Path\nfrom threading import Lock\nfrom typing import Set\n\nfrom injector import inject\nfrom more_itertools import only\nfrom watchdog.events import (\n    EVENT_TYPE_CREATED,\n    EVENT_TYPE_DELETED,\n    DirCreatedEvent,\n    DirDeletedEvent,\n    FileSystemEvent,\n    FileSystemEventHandler,\n)\n\nfrom refind_btrfs.common import ConfigurableMixin\nfrom refind_btrfs.common.abc.factories import (\n    BaseLoggerFactory,\n    BaseSubvolumeCommandFactory,\n)\nfrom refind_btrfs.common.abc.providers import (\n    BasePackageConfigProvider,\n    BasePersistenceProvider,\n)\nfrom refind_btrfs.common.exceptions import SnapshotExcludedFromDeletionError\nfrom refind_btrfs.device import Subvolume\nfrom refind_btrfs.state_management import RefindBtrfsMachine\nfrom refind_btrfs.utility.helpers import (\n    checked_cast,\n    discern_distance_between,\n    has_items,\n)\n\n\nclass SnapshotEventHandler(FileSystemEventHandler, ConfigurableMixin):\n    @inject\n    def __init__(\n        self,\n        logger_factory: BaseLoggerFactory,\n        subvolume_command_factory: BaseSubvolumeCommandFactory,\n        package_config_provider: BasePackageConfigProvider,\n        persistence_provider: BasePersistenceProvider,\n        machine: RefindBtrfsMachine,\n    ) -> None:\n        ConfigurableMixin.__init__(self, package_config_provider)\n\n        self._logger = logger_factory.logger(__name__)\n        self._subvolume_command_factory = subvolume_command_factory\n        self._persistence_provider = persistence_provider\n        self._machine = machine\n        self._deleted_snapshots: Set[Subvolume] = set()\n        self._deletion_lock = Lock()\n        self._event_lock = Lock()\n\n    def on_created(self, event: FileSystemEvent) -> None:\n        is_dir_created_event = (\n            event.event_type == EVENT_TYPE_CREATED and event.is_directory\n        )\n\n        if is_dir_created_event:\n            dir_created_event = checked_cast(DirCreatedEvent, event)\n            logger = self._logger\n            created_directory = Path(dir_created_event.src_path)\n\n            if self._is_snapshot_created(created_directory):\n                machine = self._machine\n\n                logger.info(f\"The '{created_directory}' snapshot has been created.\")\n\n                with self._event_lock:\n                    machine.run()\n\n    def on_deleted(self, event: FileSystemEvent) -> None:\n        is_dir_deleted_event = (\n            event.event_type == EVENT_TYPE_DELETED and event.is_directory\n        )\n\n        if is_dir_deleted_event:\n            dir_deleted_event = checked_cast(DirDeletedEvent, event)\n            logger = self._logger\n            deleted_directory = Path(dir_deleted_event.src_path)\n\n            try:\n                if self._is_snapshot_deleted(deleted_directory):\n                    machine = self._machine\n\n                    logger.info(f\"The '{deleted_directory}' snapshot has been deleted.\")\n\n                    with self._event_lock:\n                        machine.run()\n\n            except SnapshotExcludedFromDeletionError as e:\n                logger.warning(e.formatted_message)\n\n    def _is_snapshot_created(self, created_directory: Path) -> bool:\n        snapshot_searches = self.package_config.snapshot_searches\n        parents = created_directory.parents\n\n        for snapshot_search in snapshot_searches:\n            search_directory = snapshot_search.directory\n\n            if snapshot_search.directory in parents:\n                distance = discern_distance_between(\n                    (search_directory, created_directory)\n                )\n\n                if distance is not None:\n                    max_depth = snapshot_search.max_depth - distance\n\n                    if self._is_or_contains_snapshot(created_directory, max_depth):\n                        return True\n\n        return False\n\n    def _is_snapshot_deleted(self, deleted_directory: Path) -> bool:\n        persistence_provider = self._persistence_provider\n        previous_run_result = persistence_provider.get_previous_run_result()\n        bootable_snapshots = previous_run_result.bootable_snapshots\n\n        if has_items(bootable_snapshots):\n            deleted_snapshot = only(\n                snapshot\n                for snapshot in bootable_snapshots\n                if snapshot.is_located_in(deleted_directory)\n            )\n\n            if deleted_snapshot is not None:\n                deleted_snapshots = self._deleted_snapshots\n                deletion_lock = self._deletion_lock\n\n                with deletion_lock:\n                    if deleted_snapshot not in deleted_snapshots:\n                        snapshot_manipulation = (\n                            self.package_config.snapshot_manipulation\n                        )\n                        cleanup_exclusion = snapshot_manipulation.cleanup_exclusion\n\n                        deleted_snapshots.add(deleted_snapshot)\n\n                        if deleted_snapshot in cleanup_exclusion:\n                            raise SnapshotExcludedFromDeletionError(\n                                f\"The deleted snapshot ('{deleted_directory}') \"\n                                \"is explicitly excluded from cleanup!\"\n                            )\n\n                        return True\n\n        return False\n\n    def _is_or_contains_snapshot(\n        self, directory: Path, max_depth: int, current_depth: int = 0\n    ) -> bool:\n        if current_depth <= max_depth:\n            subvolume_command = self._subvolume_command_factory.subvolume_command()\n            resolved_path = directory.resolve()\n            subvolume = subvolume_command.get_subvolume_from(resolved_path)\n            is_snapshot = subvolume is not None and subvolume.is_snapshot()\n\n            if is_snapshot:\n                return True\n\n            subdirectories = (child for child in directory.iterdir() if child.is_dir())\n\n            if any(\n                self._is_or_contains_snapshot(\n                    subdirectory, max_depth, current_depth + 1\n                )\n                for subdirectory in subdirectories\n            ):\n                return True\n\n        return False\n"
  },
  {
    "path": "src/refind_btrfs/service/snapshot_observer.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport queue\n\nfrom injector import inject\n\nfrom refind_btrfs.common import CheckableObserver, constants\nfrom refind_btrfs.common.abc.factories import BaseLoggerFactory\nfrom refind_btrfs.common.exceptions import SnapshotMountedAsRootError\n\n\nclass SnapshotObserver(CheckableObserver):\n    @inject\n    def __init__(self, logger_factory: BaseLoggerFactory):\n        super().__init__()\n\n        self._logger = logger_factory.logger(__name__)\n\n    def run(self) -> None:\n        logger = self._logger\n\n        while self.should_keep_running():\n            try:\n                self.dispatch_events(self.event_queue)\n            except queue.Empty:\n                continue\n            except SnapshotMountedAsRootError as e:\n                logger.warning(e.formatted_message)\n                self._exception = e\n                self.stop()\n            except Exception as e:\n                logger.exception(constants.MESSAGE_UNEXPECTED_ERROR)\n                self._exception = e\n                self.stop()\n"
  },
  {
    "path": "src/refind_btrfs/service/watchdog_runner.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport os\nimport signal\nfrom signal import signal as register_signal_handler\nfrom types import FrameType\nfrom typing import Optional\n\nimport systemd.daemon as systemd_daemon\nfrom injector import inject\nfrom pid import PidFile, PidFileAlreadyRunningError\nfrom watchdog.events import FileSystemEventHandler\n\nfrom refind_btrfs.common import CheckableObserver, constants\nfrom refind_btrfs.common.abc import BaseRunner\nfrom refind_btrfs.common.abc.factories import BaseLoggerFactory\nfrom refind_btrfs.common.abc.providers import BasePackageConfigProvider\nfrom refind_btrfs.common.exceptions import SnapshotMountedAsRootError\nfrom refind_btrfs.utility.helpers import checked_cast\n\n\nclass WatchdogRunner(BaseRunner):\n    @inject\n    def __init__(\n        self,\n        logger_factory: BaseLoggerFactory,\n        package_config_provider: BasePackageConfigProvider,\n        observer: CheckableObserver,\n        event_handler: FileSystemEventHandler,\n    ) -> None:\n        self._logger = logger_factory.logger(__name__)\n        self._package_config_provider = package_config_provider\n        self._observer = observer\n        self._snapshot_event_handler = event_handler\n        self._current_pid = os.getpid()\n\n        register_signal_handler(signal.SIGTERM, self._terminate)\n\n    def run(self) -> int:\n        logger = self._logger\n        package_config_provider = self._package_config_provider\n        observer = self._observer\n        event_handler = self._snapshot_event_handler\n        current_pid = self._current_pid\n        exit_code = os.EX_OK\n\n        try:\n            with PidFile(\n                pidname=constants.BACKGROUND_MODE_PID_NAME, lock_pidfile=False\n            ) as pid_file:\n                current_pid = pid_file.pid\n                package_config = package_config_provider.get_config()\n                directories_for_watch = [\n                    str(directory)\n                    for directory in sorted(package_config.directories_for_watch)\n                ]\n\n                logger.info(\n                    \"Scheduling watch for directories: \"\n                    f\"{constants.DEFAULT_ITEMS_SEPARATOR.join(directories_for_watch)}.\"\n                )\n\n                for directory in directories_for_watch:\n                    observer.schedule(\n                        event_handler,\n                        directory,\n                        recursive=False,\n                    )\n\n                logger.info(f\"Starting the observer with PID {current_pid}.\")\n\n                observer.start()\n                systemd_daemon.notify(constants.NOTIFICATION_READY, pid=current_pid)\n\n                while observer.is_alive():\n                    observer.join(constants.WATCH_TIMEOUT)\n\n                observer.join()\n        except PidFileAlreadyRunningError as e:\n            exit_code = constants.EX_NOT_OK\n            running_pid = checked_cast(int, e.pid)\n\n            logger.error(e.message)\n            systemd_daemon.notify(\n                constants.NOTIFICATION_STATUS.format(\n                    f\"Detected an attempt to run subsequently with PID {current_pid}.\"\n                ),\n                pid=running_pid,\n            )\n        else:\n            try:\n                observer.check()\n            except SnapshotMountedAsRootError:\n                pass\n            except Exception:\n                exit_code = constants.EX_NOT_OK\n\n        if exit_code != os.EX_OK:\n            systemd_daemon.notify(\n                constants.NOTIFICATION_ERRNO.format(exit_code), pid=current_pid\n            )\n\n        return exit_code\n\n    # pylint: disable=unused-argument\n    def _terminate(self, signal_number: int, frame: Optional[FrameType]) -> None:\n        logger = self._logger\n        observer = self._observer\n        current_pid = self._current_pid\n\n        logger.info(\n            f\"Received terminating signal {signal_number}, stopping the observer...\"\n        )\n        systemd_daemon.notify(constants.NOTIFICATION_STOPPING, pid=current_pid)\n\n        if observer.is_alive():\n            observer.stop()\n            observer.join()\n"
  },
  {
    "path": "src/refind_btrfs/state_management/__init__.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom .model import Model\nfrom .refind_btrfs_machine import RefindBtrfsMachine, States\n"
  },
  {
    "path": "src/refind_btrfs/state_management/conditions.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nfrom itertools import groupby\nfrom typing import TYPE_CHECKING\n\nfrom refind_btrfs.common import constants\nfrom refind_btrfs.common.abc.factories import BaseLoggerFactory\nfrom refind_btrfs.common.enums import ConfigInitializationType\nfrom refind_btrfs.common.exceptions import (\n    NoChangesDetectedError,\n    RefindConfigError,\n    SnapshotMountedAsRootError,\n    SubvolumeError,\n)\nfrom refind_btrfs.utility.helpers import (\n    has_items,\n    is_singleton,\n    item_count_suffix,\n    none_throws,\n)\n\nif TYPE_CHECKING:\n    from .model import Model\n\n\nclass Conditions:\n    def __init__(self, logger_factory: BaseLoggerFactory, model: Model) -> None:\n        self._logger = logger_factory.logger(__name__)\n        self._model = model\n\n    def check_filtered_block_devices(self) -> bool:\n        logger = self._logger\n        model = self._model\n        esp_device = model.esp_device\n\n        if esp_device is None:\n            logger.error(\"Could not find the ESP!\")\n\n            return False\n\n        esp = model.esp\n        esp_filesystem = none_throws(esp.filesystem)\n\n        logger.info(\n            f\"Found the ESP mounted at '{esp_filesystem.mount_point}' on '{esp.name}'.\"\n        )\n\n        root_device = model.root_device\n\n        if root_device is None:\n            logger.error(\"Could not find the root partition!\")\n\n            return False\n\n        root_partition = model.root_partition\n        root_filesystem = none_throws(root_partition.filesystem)\n\n        logger.info(f\"Found the root partition on '{root_partition.name}'.\")\n\n        btrfs_type = constants.BTRFS_TYPE\n\n        if not root_filesystem.is_of_type(btrfs_type):\n            logger.error(f\"The root partition's filesystem is not '{btrfs_type}'!\")\n\n            return False\n\n        boot_device = model.boot_device\n\n        if boot_device is not None:\n            boot = none_throws(esp_device.boot)\n\n            logger.info(f\"Found a separate boot partition on '{boot.name}'.\")\n\n        return True\n\n    def check_root_subvolume(self) -> bool:\n        logger = self._logger\n        model = self._model\n        root_partition = model.root_partition\n        filesystem = none_throws(root_partition.filesystem)\n\n        if not filesystem.has_subvolume():\n            logger.error(\"The root partition is not mounted as a subvolume!\")\n\n            return False\n\n        subvolume = none_throws(filesystem.subvolume)\n        logical_path = subvolume.logical_path\n\n        logger.info(f\"Found subvolume '{logical_path}' mounted as the root partition.\")\n\n        if subvolume.is_snapshot():\n            package_config = model.package_config\n\n            if package_config.exit_if_root_is_snapshot:\n                parent_uuid = subvolume.parent_uuid\n\n                raise SnapshotMountedAsRootError(\n                    f\"Subvolume '{logical_path}' is itself a snapshot \"\n                    f\"(parent UUID - '{parent_uuid}'), exiting...\"\n                )\n\n        if not subvolume.has_snapshots():\n            logger.error(f\"No snapshots of the '{logical_path}' subvolume were found!\")\n\n            return False\n\n        snapshots = none_throws(subvolume.snapshots)\n        suffix = item_count_suffix(snapshots)\n\n        logger.info(\n            f\"Found {len(snapshots)} snapshot{suffix} of the '{logical_path}' subvolume.\"\n        )\n\n        return True\n\n    def check_matched_boot_stanzas(self) -> bool:\n        logger = self._logger\n        model = self._model\n        matched_boot_stanzas = model.matched_boot_stanzas\n\n        if not has_items(matched_boot_stanzas):\n            logger.error(\n                \"Could not find a boot stanza matched with the root partition!\"\n            )\n\n            return False\n\n        suffix = item_count_suffix(matched_boot_stanzas)\n\n        logger.info(\n            f\"Found {len(matched_boot_stanzas)} boot \"\n            f\"stanza{suffix} matched with the root partition.\"\n        )\n\n        grouping_result = groupby(matched_boot_stanzas)\n\n        for key, grouper in grouping_result:\n            grouped_boot_stanzas = list(grouper)\n\n            if not is_singleton(grouped_boot_stanzas):\n                volume = key.volume\n                loader_path = key.loader_path\n\n                logger.error(\n                    f\"Found {len(grouped_boot_stanzas)} boot stanzas defined with \"\n                    f\"the same volume ('{volume}') and loader ('{loader_path}') options!\"\n                )\n\n                return False\n\n        package_config = model.package_config\n        boot_stanza_generation = package_config.boot_stanza_generation\n        icon_generation_mode = boot_stanza_generation.icon.mode\n\n        for boot_stanza in matched_boot_stanzas:\n            try:\n                boot_stanza.validate_boot_files_check_result()\n            except RefindConfigError as e:\n                logger.warning(e.formatted_message)\n\n            boot_stanza.validate_icon_path(icon_generation_mode)\n\n        usable_boot_stanzas = model.usable_boot_stanzas\n\n        if not has_items(usable_boot_stanzas):\n            logger.error(\"None of the matched boot stanzas are usable!\")\n\n            return False\n\n        return True\n\n    def check_prepared_snapshots(self) -> bool:\n        logger = self._logger\n        model = self._model\n        prepared_snapshots = model.prepared_snapshots\n        snapshots_for_addition = prepared_snapshots.snapshots_for_addition\n        snapshots_for_removal = prepared_snapshots.snapshots_for_removal\n\n        if has_items(snapshots_for_addition):\n            subvolume = model.root_subvolume\n            suffix = item_count_suffix(snapshots_for_addition)\n\n            logger.info(\n                f\"Found {len(snapshots_for_addition)} snapshot{suffix} for addition.\"\n            )\n\n            for snapshot in snapshots_for_addition:\n                try:\n                    snapshot.validate_static_partition_table(subvolume)\n                except SubvolumeError as e:\n                    logger.warning(e.formatted_message)\n\n            usable_snapshots_for_addition = model.usable_snapshots_for_addition\n\n            if not has_items(usable_snapshots_for_addition):\n                logger.warning(\"None of the snapshots for addition are usable!\")\n\n        if has_items(snapshots_for_removal):\n            suffix = item_count_suffix(snapshots_for_removal)\n\n            logger.info(\n                f\"Found {len(snapshots_for_removal)} snapshot{suffix} for removal.\"\n            )\n\n        return True\n\n    def check_boot_stanzas_with_snapshots(self) -> bool:\n        logger = self._logger\n        model = self._model\n        boot_stanzas_with_snapshots = model.boot_stanzas_with_snapshots\n        excluded_boot_stanzas_count = len(\n            list(item for item in boot_stanzas_with_snapshots if item.is_excluded)\n        )\n\n        if len(boot_stanzas_with_snapshots) == excluded_boot_stanzas_count:\n            logger.error(\n                \"All of the matched boot stanzas are \"\n                \"explicitly excluded from processing!\"\n            )\n\n            return False\n\n        for item in boot_stanzas_with_snapshots:\n            boot_stanza = item.boot_stanza\n            normalized_name = boot_stanza.normalized_name\n\n            if item.is_excluded:\n                logger.info(\n                    f\"Skipping the '{normalized_name}' boot stanza \"\n                    \"because it is explicitly excluded from processing.\"\n                )\n            elif item.has_unmatched_snapshots():\n                unmatched_snapshots = item.unmatched_snapshots\n\n                for snapshot in unmatched_snapshots:\n                    try:\n                        snapshot.validate_boot_files_check_result()\n                    except SubvolumeError as e:\n                        logger.warning(e.formatted_message)\n\n                if not item.has_matched_snapshots():\n                    logger.warning(\n                        \"None of the prepared snapshots are matched \"\n                        f\"with the '{normalized_name}' boot stanza!\"\n                    )\n\n        usable_boot_stanzas_with_snapshots = model.usable_boot_stanzas_with_snapshots\n\n        if not has_items(usable_boot_stanzas_with_snapshots):\n            logger.error(\n                \"None of the matched boot stanzas can be \"\n                \"combined with any of the prepared snapshots!\"\n            )\n\n            return False\n\n        package_config = model.package_config\n\n        if package_config.exit_if_no_changes_are_detected:\n            refind_config = model.refind_config\n            prepared_snapshots = model.prepared_snapshots\n            has_changes = (\n                package_config.is_of_initialization_type(\n                    ConfigInitializationType.PARSED\n                )\n                or refind_config.is_of_initialization_type(\n                    ConfigInitializationType.PARSED\n                )\n                or prepared_snapshots.has_changes()\n            )\n\n            if not has_changes:\n                raise NoChangesDetectedError(\"No changes were detected, aborting...\")\n\n        return True\n"
  },
  {
    "path": "src/refind_btrfs/state_management/model.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom __future__ import annotations\n\nfrom itertools import chain\nfrom typing import Callable, NamedTuple, Optional, Self\n\nfrom injector import inject\nfrom more_itertools import only\n\nfrom refind_btrfs.boot import BootStanza, RefindConfig\nfrom refind_btrfs.common import ConfigurableMixin\nfrom refind_btrfs.common.abc.factories import (\n    BaseDeviceCommandFactory,\n    BaseIconCommandFactory,\n    BaseLoggerFactory,\n    BaseSubvolumeCommandFactory,\n)\nfrom refind_btrfs.common.abc.providers import (\n    BasePackageConfigProvider,\n    BasePersistenceProvider,\n    BaseRefindConfigProvider,\n)\nfrom refind_btrfs.device import BlockDevice, Partition, Subvolume\nfrom refind_btrfs.utility.helpers import has_items, none_throws, replace_item_in\n\nfrom .conditions import Conditions\n\n# region Helper Tuples\n\n\nclass BlockDevices(NamedTuple):\n    esp_device: Optional[BlockDevice]\n    root_device: Optional[BlockDevice]\n    boot_device: Optional[BlockDevice]\n\n    @classmethod\n    def none(cls) -> Self:\n        return cls(None, None, None)\n\n\nclass PreparedSnapshots(NamedTuple):\n    snapshots_for_addition: list[Subvolume]\n    snapshots_for_removal: list[Subvolume]\n\n    def has_changes(self) -> bool:\n        return has_items(self.snapshots_for_addition) or has_items(\n            self.snapshots_for_removal\n        )\n\n\nclass BootStanzaWithSnapshots(NamedTuple):\n    boot_stanza: BootStanza\n    is_excluded: bool\n    matched_snapshots: list[Subvolume]\n    unmatched_snapshots: list[Subvolume]\n\n    def has_matched_snapshots(self) -> bool:\n        return has_items(self.matched_snapshots)\n\n    def has_unmatched_snapshots(self) -> bool:\n        return has_items(self.unmatched_snapshots)\n\n    def is_usable(self) -> bool:\n        return not self.is_excluded and self.has_matched_snapshots()\n\n    def replace_matched_snapshot(\n        self, current_snapshot: Subvolume, replacement_snapshot: Subvolume\n    ) -> None:\n        matched_snapshots = self.matched_snapshots\n\n        replace_item_in(matched_snapshots, current_snapshot, replacement_snapshot)\n\n\nclass ProcessingResult(NamedTuple):\n    bootable_snapshots: list[Subvolume]\n\n    @classmethod\n    def none(cls) -> Self:\n        return cls([])\n\n    def has_bootable_snapshots(self) -> bool:\n        return has_items(self.bootable_snapshots)\n\n\n# endregion\n\n\nclass Model(ConfigurableMixin):\n    @inject\n    def __init__(\n        self,\n        logger_factory: BaseLoggerFactory,\n        device_command_factory: BaseDeviceCommandFactory,\n        subvolume_command_factory: BaseSubvolumeCommandFactory,\n        icon_command_factory: BaseIconCommandFactory,\n        package_config_provider: BasePackageConfigProvider,\n        refind_config_provider: BaseRefindConfigProvider,\n        persistence_provider: BasePersistenceProvider,\n    ) -> None:\n        ConfigurableMixin.__init__(self, package_config_provider)\n\n        self._device_command_factory = device_command_factory\n        self._subvolume_command_factory = subvolume_command_factory\n        self._icon_command_factory = icon_command_factory\n        self._refind_config_provider = refind_config_provider\n        self._persistence_provider = persistence_provider\n        self._conditions = Conditions(logger_factory, self)\n        self._filtered_block_devices: Optional[BlockDevices] = None\n        self._matched_boot_stanzas: Optional[list[BootStanza]] = None\n        self._prepared_snapshots: Optional[PreparedSnapshots] = None\n        self._boot_stanzas_with_snapshots: Optional[\n            list[BootStanzaWithSnapshots]\n        ] = None\n\n    def initialize_block_devices(self) -> None:\n        device_command_factory = self._device_command_factory\n        physical_device_command = device_command_factory.physical_device_command()\n        all_block_devices = list(physical_device_command.get_block_devices())\n\n        if has_items(all_block_devices):\n            for block_device in all_block_devices:\n                block_device.initialize_partition_tables_using(device_command_factory)\n\n            def block_device_filter(\n                filter_func: Callable[[BlockDevice], bool],\n            ) -> Optional[BlockDevice]:\n                return only(\n                    block_device\n                    for block_device in all_block_devices\n                    if filter_func(block_device)\n                )\n\n            filtered_block_devices = BlockDevices(\n                block_device_filter(BlockDevice.has_esp),\n                block_device_filter(BlockDevice.has_root),\n                block_device_filter(BlockDevice.has_boot),\n            )\n        else:\n            filtered_block_devices = BlockDevices.none()\n\n        self._filtered_block_devices = filtered_block_devices\n\n    def initialize_root_subvolume(self) -> None:\n        subvolume_command_factory = self._subvolume_command_factory\n        root_partition = self.root_partition\n        filesystem = none_throws(root_partition.filesystem)\n\n        filesystem.initialize_subvolume_using(subvolume_command_factory)\n\n    def initialize_matched_boot_stanzas(self) -> None:\n        refind_config = self.refind_config\n        include_paths = self._should_include_paths_during_generation()\n        root_device = none_throws(self.root_device)\n        matched_boot_stanzas = refind_config.get_boot_stanzas_matched_with(root_device)\n\n        if include_paths:\n            subvolume = self.root_subvolume\n            include_sub_menus = self._should_include_sub_menus_during_generation()\n\n            self._matched_boot_stanzas = [\n                boot_stanza.with_boot_files_check_result(subvolume, include_sub_menus)\n                for boot_stanza in matched_boot_stanzas\n            ]\n        else:\n            self._matched_boot_stanzas = list(matched_boot_stanzas)\n\n    def initialize_prepared_snapshots(self) -> None:\n        persistence_provider = self._persistence_provider\n        snapshot_manipulation = self.package_config.snapshot_manipulation\n        subvolume = self.root_subvolume\n        previous_run_result = persistence_provider.get_previous_run_result()\n        selected_snapshots = none_throws(\n            subvolume.select_snapshots(snapshot_manipulation.selection_count)\n        )\n        destination_directory = snapshot_manipulation.destination_directory\n        snapshots_union = snapshot_manipulation.cleanup_exclusion.union(\n            selected_snapshots\n        )\n\n        if previous_run_result.has_bootable_snapshots():\n            bootable_snapshots = previous_run_result.bootable_snapshots\n            snapshots_for_addition = [\n                snapshot\n                for snapshot in selected_snapshots\n                if snapshot.can_be_added(bootable_snapshots)\n            ]\n            snapshots_for_removal = [\n                snapshot\n                for snapshot in bootable_snapshots\n                if snapshot.can_be_removed(destination_directory, snapshots_union)\n            ]\n        else:\n            destination_snapshots = self.destination_snapshots\n            snapshots_for_addition = selected_snapshots\n            snapshots_for_removal = [\n                snapshot\n                for snapshot in destination_snapshots.difference(snapshots_union)\n                if snapshot.can_be_removed(destination_directory, selected_snapshots)\n            ]\n\n        if has_items(snapshots_for_addition):\n            device_command_factory = self._device_command_factory\n\n            for snapshot in snapshots_for_addition:\n                snapshot.initialize_partition_table_using(device_command_factory)\n\n        self._prepared_snapshots = PreparedSnapshots(\n            snapshots_for_addition, snapshots_for_removal\n        )\n\n    def combine_boot_stanzas_with_snapshots(self) -> None:\n        usable_boot_stanzas = self.usable_boot_stanzas\n        actual_bootable_snapshots = self.actual_bootable_snapshots\n        boot_stanza_generation = self.package_config.boot_stanza_generation\n        include_paths = self._should_include_paths_during_generation()\n        boot_stanza_preparation_results: list[BootStanzaWithSnapshots] = []\n\n        for boot_stanza in usable_boot_stanzas:\n            is_excluded = any(\n                boot_stanza.is_matched_with(loader_filename)\n                for loader_filename in boot_stanza_generation.source_exclusion\n            )\n            matched_snapshots: list[Subvolume] = []\n            unmatched_snapshots: list[Subvolume] = []\n\n            if include_paths:\n                checked_bootable_snapshots = (\n                    snapshot.with_boot_files_check_result(boot_stanza)\n                    for snapshot in actual_bootable_snapshots\n                )\n\n                for snapshot in checked_bootable_snapshots:\n                    append_func = (\n                        unmatched_snapshots.append\n                        if snapshot.has_unmatched_boot_files()\n                        else matched_snapshots.append\n                    )\n\n                    append_func(snapshot)\n            else:\n                matched_snapshots.extend(actual_bootable_snapshots)\n\n            boot_stanza_preparation_results.append(\n                BootStanzaWithSnapshots(\n                    boot_stanza, is_excluded, matched_snapshots, unmatched_snapshots\n                )\n            )\n\n        self._boot_stanzas_with_snapshots = boot_stanza_preparation_results\n\n    def process_changes(self) -> None:\n        persistence_provider = self._persistence_provider\n        bootable_snapshots = self._process_snapshots()\n\n        self._process_boot_stanzas()\n\n        persistence_provider.save_current_run_result(\n            ProcessingResult(bootable_snapshots)\n        )\n\n    def _process_snapshots(self) -> list[Subvolume]:\n        subvolume_command_factory = self._subvolume_command_factory\n        actual_bootable_snapshots = self.actual_bootable_snapshots\n        usable_snapshots_for_addition = self.usable_snapshots_for_addition\n        subvolume_command = subvolume_command_factory.subvolume_command()\n\n        if has_items(usable_snapshots_for_addition):\n            device_command_factory = self._device_command_factory\n            subvolume = self.root_subvolume\n            boot_stanzas_with_snapshots = self.boot_stanzas_with_snapshots\n            all_usable_snapshots = set(\n                chain.from_iterable(self.usable_boot_stanzas_with_snapshots.values())\n            )\n\n            for addition in usable_snapshots_for_addition:\n                if addition in all_usable_snapshots:\n                    bootable_snapshot = subvolume_command.get_bootable_snapshot_from(\n                        addition\n                    )\n\n                    bootable_snapshot.modify_partition_table_using(\n                        subvolume, device_command_factory\n                    )\n                    replace_item_in(\n                        actual_bootable_snapshots, addition, bootable_snapshot\n                    )\n\n                    for item in boot_stanzas_with_snapshots:\n                        item.replace_matched_snapshot(addition, bootable_snapshot)\n                else:\n                    actual_bootable_snapshots.remove(addition)\n\n        prepared_snapshots = self.prepared_snapshots\n        snapshots_for_removal = prepared_snapshots.snapshots_for_removal\n\n        if has_items(snapshots_for_removal):\n            for removal in snapshots_for_removal:\n                subvolume_command.delete_snapshot(removal)\n\n        return actual_bootable_snapshots\n\n    def _process_boot_stanzas(self) -> None:\n        refind_config = self.refind_config\n        root_device = none_throws(self.root_device)\n        boot_device = self.boot_device\n        usable_boot_stanzas_with_snapshots = self.usable_boot_stanzas_with_snapshots\n        boot_stanza_generation = (\n            self.package_config.boot_stanza_generation.with_include_paths(boot_device)\n        )\n        icon_command_factory = self._icon_command_factory\n        generated_refind_configs = refind_config.generate_new_from(\n            root_device,\n            usable_boot_stanzas_with_snapshots,\n            boot_stanza_generation,\n            icon_command_factory,\n        )\n\n        refind_config_provider = self._refind_config_provider\n\n        for generated_refind_config in generated_refind_configs:\n            refind_config_provider.save_config(generated_refind_config)\n\n        refind_config_provider.append_to_config(refind_config)\n\n    def _should_include_paths_during_generation(self) -> bool:\n        boot_stanza_generation = self.package_config.boot_stanza_generation\n\n        if boot_stanza_generation.include_paths:\n            return self.boot_device is None\n\n        return False\n\n    def _should_include_sub_menus_during_generation(self) -> bool:\n        boot_stanza_generation = self.package_config.boot_stanza_generation\n\n        return boot_stanza_generation.include_sub_menus\n\n    @property\n    def conditions(self) -> list[Callable[[], bool]]:\n        conditions = self._conditions\n        always_true_func = lambda: True\n\n        return [\n            always_true_func,\n            conditions.check_filtered_block_devices,\n            conditions.check_root_subvolume,\n            conditions.check_matched_boot_stanzas,\n            conditions.check_prepared_snapshots,\n            conditions.check_boot_stanzas_with_snapshots,\n            always_true_func,\n        ]\n\n    @property\n    def refind_config(self) -> RefindConfig:\n        refind_config_provider = self._refind_config_provider\n        esp = self.esp\n\n        return refind_config_provider.get_config(esp)\n\n    @property\n    def esp_device(self) -> Optional[BlockDevice]:\n        return none_throws(self._filtered_block_devices).esp_device\n\n    @property\n    def esp(self) -> Partition:\n        esp_device = none_throws(self.esp_device)\n\n        return none_throws(esp_device.esp)\n\n    @property\n    def root_device(self) -> Optional[BlockDevice]:\n        return none_throws(self._filtered_block_devices).root_device\n\n    @property\n    def root_partition(self) -> Partition:\n        root_device = none_throws(self.root_device)\n\n        return none_throws(root_device.root)\n\n    @property\n    def root_subvolume(self) -> Subvolume:\n        root_partition = self.root_partition\n        filesystem = none_throws(root_partition.filesystem)\n\n        return none_throws(filesystem.subvolume)\n\n    @property\n    def boot_device(self) -> Optional[BlockDevice]:\n        return none_throws(self._filtered_block_devices).boot_device\n\n    @property\n    def matched_boot_stanzas(self) -> list[BootStanza]:\n        return none_throws(self._matched_boot_stanzas)\n\n    @property\n    def usable_boot_stanzas(self) -> list[BootStanza]:\n        matched_boot_stanzas = self.matched_boot_stanzas\n\n        return [\n            boot_stanza\n            for boot_stanza in matched_boot_stanzas\n            if not boot_stanza.has_unmatched_boot_files()\n        ]\n\n    @property\n    def prepared_snapshots(self) -> PreparedSnapshots:\n        return none_throws(self._prepared_snapshots)\n\n    @property\n    def destination_snapshots(self) -> set[Subvolume]:\n        subvolume_command_factory = self._subvolume_command_factory\n        subvolume_command = subvolume_command_factory.subvolume_command()\n        destination_snapshots = sorted(\n            subvolume_command.get_all_destination_snapshots(), reverse=True\n        )\n\n        return set(destination_snapshots)\n\n    @property\n    def usable_snapshots_for_addition(self) -> list[Subvolume]:\n        subvolume = self.root_subvolume\n        prepared_snapshots = self.prepared_snapshots\n        snapshots_for_addition = prepared_snapshots.snapshots_for_addition\n\n        return [\n            snapshot\n            for snapshot in snapshots_for_addition\n            if snapshot.is_static_partition_table_matched_with(subvolume)\n        ]\n\n    @property\n    def actual_bootable_snapshots(self) -> list[Subvolume]:\n        persistence_provider = self._persistence_provider\n        prepared_snapshots = self.prepared_snapshots\n        usable_snapshots_for_addition = self.usable_snapshots_for_addition\n        previous_run_result = persistence_provider.get_previous_run_result()\n        snapshots_for_removal = prepared_snapshots.snapshots_for_removal\n        bootable_snapshots = set(previous_run_result.bootable_snapshots)\n\n        if has_items(usable_snapshots_for_addition):\n            bootable_snapshots |= set(usable_snapshots_for_addition)\n\n        if has_items(snapshots_for_removal):\n            bootable_snapshots -= set(snapshots_for_removal)\n\n        return list(bootable_snapshots)\n\n    @property\n    def boot_stanzas_with_snapshots(self) -> list[BootStanzaWithSnapshots]:\n        return none_throws(self._boot_stanzas_with_snapshots)\n\n    @property\n    def usable_boot_stanzas_with_snapshots(self) -> dict[BootStanza, list[Subvolume]]:\n        boot_stanzas_with_snapshots = self.boot_stanzas_with_snapshots\n\n        return {\n            item.boot_stanza: item.matched_snapshots\n            for item in boot_stanzas_with_snapshots\n            if item.is_usable()\n        }\n"
  },
  {
    "path": "src/refind_btrfs/state_management/refind_btrfs_machine.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom typing import Collection\n\nfrom injector import inject\nfrom more_itertools import first, last\nfrom transitions import Machine, State\n\nfrom refind_btrfs.common.abc.factories import BaseLoggerFactory\nfrom refind_btrfs.common.enums import StateNames\nfrom refind_btrfs.common.exceptions import (\n    NoChangesDetectedError,\n    PartitionError,\n    RefindConfigError,\n    SubvolumeError,\n)\nfrom refind_btrfs.utility.helpers import checked_cast, has_items, is_singleton\n\nfrom .model import Model\n\nStates = Collection[State]\n\n\nclass RefindBtrfsMachine(Machine):\n    @inject\n    def __init__(\n        self,\n        logger_factory: BaseLoggerFactory,\n        model: Model,\n        states: States,\n    ):\n        self._logger = logger_factory.logger(__name__)\n\n        if not has_items(states) or is_singleton(states):\n            raise ValueError(\n                \"The 'states' collection must be initialized and contain at least two items!\"\n            )\n\n        initial = checked_cast(State, first(states))\n        expected_initial_name = StateNames.INITIAL.value\n\n        if initial.name != expected_initial_name:\n            raise ValueError(\n                \"The first item of the 'states' collection must \"\n                f\"be a state named '{expected_initial_name}'!\"\n            )\n\n        final = checked_cast(State, last(states))\n        expected_final_name = StateNames.FINAL.value\n\n        if final.name != expected_final_name:\n            raise ValueError(\n                \"The last item of the 'states' collection must \"\n                f\"be a state named '{expected_final_name}'!\"\n            )\n\n        conditions = model.conditions\n\n        super().__init__(\n            model=model,\n            states=list(states),\n            initial=initial,\n            auto_transitions=False,\n            name=__name__,\n        )\n        self.add_ordered_transitions(\n            loop=False,\n            conditions=conditions,\n        )\n\n        self._initial_state = initial\n\n    def run(self) -> bool:\n        logger = self._logger\n        model = self.model\n        initial_state = self._initial_state\n\n        self.set_state(initial_state)\n\n        try:\n            while model.next_state():\n                if model.is_final():\n                    return True\n        except NoChangesDetectedError as e:\n            logger.warning(e.formatted_message)\n            return True\n        except (\n            PartitionError,\n            SubvolumeError,\n            RefindConfigError,\n        ) as e:\n            logger.error(e.formatted_message)\n\n        return False\n"
  },
  {
    "path": "src/refind_btrfs/system/__init__.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom .command_factories import (\n    BtrfsUtilSubvolumeCommandFactory,\n    PillowIconCommandFactory,\n    SystemDeviceCommandFactory,\n)\n"
  },
  {
    "path": "src/refind_btrfs/system/btrfsutil_command.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom datetime import datetime\nfrom pathlib import Path\nfrom typing import Iterator, Optional, Set\n\nimport btrfsutil\n\nfrom refind_btrfs.common import ConfigurableMixin, constants\nfrom refind_btrfs.common.abc.commands import SubvolumeCommand\nfrom refind_btrfs.common.abc.factories import BaseLoggerFactory\nfrom refind_btrfs.common.abc.providers import BasePackageConfigProvider\nfrom refind_btrfs.common.exceptions import SubvolumeError\nfrom refind_btrfs.device import NumIdRelation, Subvolume, UuidRelation\nfrom refind_btrfs.utility.helpers import (\n    checked_cast,\n    default_if_none,\n    none_throws,\n    try_convert_bytes_to_uuid,\n)\n\n\nclass BtrfsUtilCommand(SubvolumeCommand, ConfigurableMixin):\n    def __init__(\n        self,\n        logger_factory: BaseLoggerFactory,\n        package_config_provider: BasePackageConfigProvider,\n    ) -> None:\n        ConfigurableMixin.__init__(self, package_config_provider)\n\n        self._logger = logger_factory.logger(__name__)\n        self._searched_directories: Set[Path] = set()\n\n    def get_subvolume_from(self, filesystem_path: Path) -> Optional[Subvolume]:\n        logger = self._logger\n\n        if not filesystem_path.exists():\n            raise SubvolumeError(f\"The '{filesystem_path}' path does not exist!\")\n\n        if not filesystem_path.is_dir():\n            raise SubvolumeError(\n                f\"The '{filesystem_path}' path does not represent a directory!\"\n            )\n\n        try:\n            filesystem_path_str = str(filesystem_path)\n\n            if btrfsutil.is_subvolume(filesystem_path_str):\n                subvolume_id = btrfsutil.subvolume_id(filesystem_path_str)\n                subvolume_path = btrfsutil.subvolume_path(\n                    filesystem_path_str, subvolume_id\n                )\n                subvolume_read_only = btrfsutil.get_subvolume_read_only(\n                    filesystem_path_str\n                )\n                subvolume_info = btrfsutil.subvolume_info(\n                    filesystem_path_str, subvolume_id\n                )\n                self_uuid = default_if_none(\n                    try_convert_bytes_to_uuid(subvolume_info.uuid),\n                    constants.EMPTY_UUID,\n                )\n                parent_uuid = default_if_none(\n                    try_convert_bytes_to_uuid(subvolume_info.parent_uuid),\n                    constants.EMPTY_UUID,\n                )\n\n                return Subvolume(\n                    filesystem_path,\n                    subvolume_path,\n                    datetime.fromtimestamp(subvolume_info.otime),\n                    UuidRelation(self_uuid, parent_uuid),\n                    NumIdRelation(subvolume_info.id, subvolume_info.parent_id),\n                    subvolume_read_only,\n                )\n        except btrfsutil.BtrfsUtilError as e:\n            logger.exception(\"btrfsutil call failed!\")\n            raise SubvolumeError(\n                f\"Could not initialize the subvolume for '{filesystem_path}'!\"\n            ) from e\n\n        return None\n\n    def get_all_source_snapshots_for(self, parent: Subvolume) -> Iterator[Subvolume]:\n        self._searched_directories.clear()\n\n        snapshot_searches = self.package_config.snapshot_searches\n\n        for snapshot_search in snapshot_searches:\n            directory = snapshot_search.directory\n            is_nested = snapshot_search.is_nested\n            max_depth = snapshot_search.max_depth\n            search_result = self._search_for_snapshots_in(\n                directory, max_depth, parent=parent\n            )\n\n            if is_nested:\n                root_directory = directory.root\n\n                for snapshot in search_result:\n                    filesystem_path = snapshot.filesystem_path\n                    nested_directory = filesystem_path / directory.relative_to(\n                        root_directory\n                    )\n\n                    if nested_directory.exists():\n                        yield from self._search_for_snapshots_in(\n                            nested_directory, max_depth, parent=parent\n                        )\n\n                    yield snapshot\n            else:\n                yield from search_result\n\n    def get_all_destination_snapshots(self) -> Iterator[Subvolume]:\n        snapshot_manipulation = self.package_config.snapshot_manipulation\n        destination_directory = snapshot_manipulation.destination_directory\n\n        if destination_directory.exists():\n            yield from self._search_for_snapshots_in(destination_directory, 1)\n\n    def get_bootable_snapshot_from(self, source: Subvolume) -> Subvolume:\n        if source.is_read_only:\n            snapshot_manipulation = self.package_config.snapshot_manipulation\n            modify_read_only_flag = snapshot_manipulation.modify_read_only_flag\n\n            if modify_read_only_flag:\n                destination = self._modify_read_only_flag_for(source)\n            else:\n                destination = self._create_writable_snapshot_from(source)\n        else:\n            destination = source\n\n        return destination.as_named()\n\n    def delete_snapshot(self, snapshot: Subvolume) -> None:\n        logger = self._logger\n        filesystem_path = snapshot.filesystem_path\n        logical_path = snapshot.logical_path\n\n        try:\n            filesystem_path_str = str(filesystem_path)\n            is_subvolume = filesystem_path.exists() and btrfsutil.is_subvolume(\n                filesystem_path_str\n            )\n\n            if is_subvolume:\n                root_dir_str = str(constants.ROOT_DIR)\n                num_id = snapshot.num_id\n                deleted_subvolumes = checked_cast(\n                    list[int], btrfsutil.deleted_subvolumes(root_dir_str)\n                )\n\n                if num_id not in deleted_subvolumes:\n                    logger.info(f\"Deleting the '{logical_path}' snapshot.\")\n\n                    btrfsutil.delete_subvolume(filesystem_path_str)\n                else:\n                    logger.warning(\n                        f\"The '{logical_path}' snapshot has already \"\n                        \"been deleted but not yet cleaned up.\"\n                    )\n            else:\n                logger.warning(f\"The '{filesystem_path}' directory is not a subvolume.\")\n        except btrfsutil.BtrfsUtilError as e:\n            logger.exception(\"btrfsutil call failed!\")\n            raise SubvolumeError(\n                f\"Could not delete the '{logical_path}' snapshot!\"\n            ) from e\n\n    def _search_for_snapshots_in(\n        self,\n        directory: Path,\n        max_depth: int,\n        current_depth: int = 0,\n        parent: Optional[Subvolume] = None,\n    ) -> Iterator[Subvolume]:\n        if current_depth > max_depth:\n            return\n\n        logger = self._logger\n        is_initial_call = not bool(current_depth)\n        resolved_path = directory.resolve()\n\n        if is_initial_call:\n            if parent is None:\n                logger.info(f\"Getting all snapshots in the '{directory}' directory.\")\n            else:\n                logical_path = parent.logical_path\n\n                logger.info(\n                    f\"Searching for snapshots of the '{logical_path}' \"\n                    f\"subvolume in the '{directory}' directory.\"\n                )\n\n        searched_directories = self._searched_directories\n\n        if resolved_path not in searched_directories:\n            subvolume = self.get_subvolume_from(resolved_path)\n            can_subvolume_be_yielded = False\n\n            if subvolume is not None:\n                can_subvolume_be_yielded = (\n                    subvolume.is_snapshot_of(parent)\n                    if parent is not None\n                    else subvolume.is_snapshot()\n                )\n\n            searched_directories.add(resolved_path)\n\n            if can_subvolume_be_yielded:\n                yield none_throws(subvolume)\n            else:\n                subdirectories = (\n                    child for child in directory.iterdir() if child.is_dir()\n                )\n\n                for subdirectory in subdirectories:\n                    yield from self._search_for_snapshots_in(\n                        subdirectory, max_depth, current_depth + 1, parent\n                    )\n\n    def _modify_read_only_flag_for(self, source: Subvolume) -> Subvolume:\n        logger = self._logger\n        source_logical_path = source.logical_path\n\n        try:\n            logger.info(\n                f\"Modifying the '{source_logical_path}' snapshot's read-only flag.\"\n            )\n\n            source_filesystem_path_str = str(source.filesystem_path)\n\n            btrfsutil.set_subvolume_read_only(source_filesystem_path_str, False)\n        except btrfsutil.BtrfsUtilError as e:\n            logger.exception(\"btrfsutil call failed!\")\n            raise SubvolumeError(\n                f\"Could not modify the '{source_logical_path}' snapshot's read-only flag!\"\n            ) from e\n\n        return source.as_writable()\n\n    def _create_writable_snapshot_from(self, source: Subvolume) -> Subvolume:\n        logger = self._logger\n        snapshot_manipulation = self.package_config.snapshot_manipulation\n        destination_directory = snapshot_manipulation.destination_directory\n\n        if not destination_directory.exists():\n            directory_permissions = constants.SNAPSHOTS_ROOT_DIR_PERMISSIONS\n            octal_permissions = \"{0:o}\".format(directory_permissions)\n\n            try:\n                logger.info(\n                    f\"Creating the '{destination_directory}' destination \"\n                    f\"directory with {octal_permissions} permissions.\"\n                )\n\n                destination_directory.mkdir(mode=directory_permissions, parents=True)\n            except OSError as e:\n                logger.exception(\"Path.mkdir() call failed!\")\n                raise SubvolumeError(\n                    f\"Could not create the '{destination_directory}' destination directory!\"\n                ) from e\n\n        destination = source.to_destination(destination_directory)\n        source_logical_path = source.logical_path\n        snapshot_directory = destination.filesystem_path\n\n        try:\n            logger.info(\n                \"Creating a new writable snapshot from the read-only \"\n                f\"'{source_logical_path}' snapshot at '{snapshot_directory}'.\"\n            )\n\n            snapshot_directory_str = str(snapshot_directory)\n            is_subvolume = snapshot_directory.exists() and btrfsutil.is_subvolume(\n                snapshot_directory_str\n            )\n\n            if not is_subvolume:\n                source_filesystem_path_str = str(source.filesystem_path)\n\n                btrfsutil.create_snapshot(\n                    source_filesystem_path_str, snapshot_directory_str, read_only=False\n                )\n            else:\n                logger.warning(\n                    f\"The '{snapshot_directory}' directory is already a subvolume.\"\n                )\n        except btrfsutil.BtrfsUtilError as e:\n            logger.exception(\"btrfsutil call failed!\")\n            raise SubvolumeError(\n                f\"Could not create a new writable snapshot at '{snapshot_directory}'!\"\n            ) from e\n\n        writable_snapshot = self.get_subvolume_from(snapshot_directory)\n\n        return none_throws(writable_snapshot).as_newly_created_from(source)\n"
  },
  {
    "path": "src/refind_btrfs/system/command_factories.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom injector import inject\n\nfrom refind_btrfs.common.abc.commands import (\n    DeviceCommand,\n    IconCommand,\n    SubvolumeCommand,\n)\nfrom refind_btrfs.common.abc.factories import (\n    BaseDeviceCommandFactory,\n    BaseIconCommandFactory,\n    BaseLoggerFactory,\n    BaseSubvolumeCommandFactory,\n)\nfrom refind_btrfs.common.abc.providers import BasePackageConfigProvider\n\nfrom .btrfsutil_command import BtrfsUtilCommand\nfrom .findmnt_command import FindmntCommand\nfrom .fstab_command import FstabCommand\nfrom .lsblk_command import LsblkCommand\nfrom .pillow_command import PillowCommand\n\n\nclass SystemDeviceCommandFactory(BaseDeviceCommandFactory):\n    @inject\n    def __init__(\n        self,\n        logger_factory: BaseLoggerFactory,\n        package_config_provider: BasePackageConfigProvider,\n    ) -> None:\n        self._logger_factory = logger_factory\n        self._package_config_provider = package_config_provider\n\n    def physical_device_command(self) -> DeviceCommand:\n        return LsblkCommand(self._logger_factory, self._package_config_provider)\n\n    def live_device_command(self) -> DeviceCommand:\n        return FindmntCommand(self._logger_factory)\n\n    def static_device_command(self) -> DeviceCommand:\n        return FstabCommand(self._logger_factory)\n\n\nclass BtrfsUtilSubvolumeCommandFactory(BaseSubvolumeCommandFactory):\n    @inject\n    def __init__(\n        self,\n        logger_factory: BaseLoggerFactory,\n        package_config_provider: BasePackageConfigProvider,\n    ) -> None:\n        self._logger_factory = logger_factory\n        self._package_config_provider = package_config_provider\n\n    def subvolume_command(self) -> SubvolumeCommand:\n        return BtrfsUtilCommand(self._logger_factory, self._package_config_provider)\n\n\nclass PillowIconCommandFactory(BaseIconCommandFactory):\n    @inject\n    def __init__(self, logger_factory: BaseLoggerFactory) -> None:\n        self._logger_factory = logger_factory\n\n    def icon_command(self) -> IconCommand:\n        return PillowCommand(self._logger_factory)\n"
  },
  {
    "path": "src/refind_btrfs/system/findmnt_command.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport json\nimport subprocess\nfrom subprocess import CalledProcessError\nfrom typing import Any, Iterable, Iterator\n\nfrom more_itertools import always_iterable\n\nfrom refind_btrfs.common import constants\nfrom refind_btrfs.common.abc.commands import DeviceCommand\nfrom refind_btrfs.common.abc.factories import BaseLoggerFactory\nfrom refind_btrfs.common.enums import FindmntColumn, FindmntJsonKey\nfrom refind_btrfs.common.exceptions import PartitionError\nfrom refind_btrfs.device import (\n    BlockDevice,\n    Filesystem,\n    Partition,\n    PartitionTable,\n    Subvolume,\n)\nfrom refind_btrfs.utility.helpers import (\n    checked_cast,\n    default_if_none,\n    is_none_or_whitespace,\n)\n\n\nclass FindmntCommand(DeviceCommand):\n    def __init__(self, logger_factory: BaseLoggerFactory) -> None:\n        self._logger = logger_factory.logger(__name__)\n\n    def get_block_devices(self) -> Iterator[BlockDevice]:\n        raise NotImplementedError(\n            f\"Class '{FindmntCommand.__name__}' does not implement the \"\n            f\"'{DeviceCommand.get_block_devices.__name__}' method!\"\n        )\n\n    # pylint: disable=unused-argument\n    def save_partition_table(self, partition_table: PartitionTable) -> None:\n        raise NotImplementedError(\n            f\"Class '{FindmntCommand.__name__}' does not implement the \"\n            f\"'{DeviceCommand.save_partition_table.__name__}' method!\"\n        )\n\n    def _block_device_partition_table(\n        self, block_device: BlockDevice\n    ) -> PartitionTable:\n        logger = self._logger\n        findmnt_columns = [\n            FindmntColumn.PART_UUID,\n            FindmntColumn.PART_LABEL,\n            FindmntColumn.FS_UUID,\n            FindmntColumn.DEVICE_NAME,\n            FindmntColumn.FS_TYPE,\n            FindmntColumn.FS_LABEL,\n            FindmntColumn.FS_MOUNT_POINT,\n            FindmntColumn.FS_MOUNT_OPTIONS,\n        ]\n        device_name = block_device.name\n        output = constants.COLUMN_SEPARATOR.join(\n            [findmnt_column_key.value.upper() for findmnt_column_key in findmnt_columns]\n        )\n        findmnt_command = f\"findmnt --json --mtab --real --nofsroot --uniq --output {output}\"\n\n        try:\n            logger.info(\n                f\"Initializing the live partition table for device '{device_name}' using findmnt.\"\n            )\n            logger.debug(f\"Running command '{findmnt_command}'.\")\n\n            findmnt_process = subprocess.run(\n                findmnt_command.split(), capture_output=True, check=True, text=True\n            )\n        except CalledProcessError as e:\n            stderr = checked_cast(str, e.stderr)\n\n            if is_none_or_whitespace(stderr):\n                message = \"findmnt execution failed!\"\n            else:\n                message = f\"findmnt execution failed: '{stderr.rstrip()}'!\"\n\n            logger.exception(message)\n            raise PartitionError(\n                f\"Could not initialize the live partition table for '{device_name}'!\"\n            ) from e\n\n        findmnt_parsed_output = json.loads(findmnt_process.stdout)\n        findmnt_partitions = (\n            findmnt_partition\n            for findmnt_partition in always_iterable(\n                findmnt_parsed_output.get(FindmntJsonKey.FILESYSTEMS.value)\n            )\n            if block_device.is_matched_with(\n                default_if_none(\n                    findmnt_partition.get(FindmntColumn.DEVICE_NAME.value),\n                    constants.EMPTY_STR,\n                )\n            )\n        )\n\n        return PartitionTable(\n            constants.EMPTY_HEX_UUID, constants.MTAB_PT_TYPE\n        ).with_partitions(FindmntCommand._map_to_partitions(findmnt_partitions))\n\n    def _subvolume_partition_table(self, subvolume: Subvolume) -> PartitionTable:\n        raise NotImplementedError(\n            f\"Class '{FindmntCommand.__name__}' does not implement the \"\n            f\"'{DeviceCommand._subvolume_partition_table.__name__}' method!\"\n        )\n\n    @staticmethod\n    def _map_to_partitions(\n        findmnt_partitions: Iterable[Any],\n    ) -> Iterator[Partition]:\n        for findmnt_partition in findmnt_partitions:\n            findmnt_part_columns = [\n                default_if_none(\n                    findmnt_partition.get(findmnt_column_key.value), constants.EMPTY_STR\n                )\n                for findmnt_column_key in [\n                    FindmntColumn.PART_UUID,\n                    FindmntColumn.DEVICE_NAME,\n                    FindmntColumn.PART_LABEL,\n                ]\n            ]\n            findmnt_fs_columns = [\n                default_if_none(\n                    findmnt_partition.get(findmnt_column_key.value), constants.EMPTY_STR\n                )\n                for findmnt_column_key in [\n                    FindmntColumn.FS_UUID,\n                    FindmntColumn.FS_LABEL,\n                    FindmntColumn.FS_TYPE,\n                    FindmntColumn.FS_MOUNT_POINT,\n                ]\n            ]\n\n            yield (\n                Partition(*findmnt_part_columns).with_filesystem(\n                    Filesystem(*findmnt_fs_columns).with_mount_options(\n                        default_if_none(\n                            findmnt_partition.get(FindmntColumn.FS_MOUNT_OPTIONS.value),\n                            constants.EMPTY_STR,\n                        )\n                    )\n                )\n            )\n"
  },
  {
    "path": "src/refind_btrfs/system/fstab_command.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport fileinput\nfrom typing import Iterator, TextIO\n\nfrom refind_btrfs.common import constants\nfrom refind_btrfs.common.abc.commands import DeviceCommand\nfrom refind_btrfs.common.abc.factories import BaseLoggerFactory\nfrom refind_btrfs.common.enums import FstabColumn\nfrom refind_btrfs.common.exceptions import PartitionError\nfrom refind_btrfs.device import (\n    BlockDevice,\n    Filesystem,\n    Partition,\n    PartitionTable,\n    Subvolume,\n)\nfrom refind_btrfs.utility.helpers import (\n    default_if_none,\n    none_throws,\n    try_parse_int,\n)\n\n\nclass FstabCommand(DeviceCommand):\n    def __init__(self, logger_factory: BaseLoggerFactory) -> None:\n        self._logger = logger_factory.logger(__name__)\n\n    def get_block_devices(self) -> Iterator[BlockDevice]:\n        raise NotImplementedError(\n            f\"Class '{FstabCommand.__name__}' does not implement the \"\n            f\"'{DeviceCommand.get_block_devices.__name__}' method!\"\n        )\n\n    def _block_device_partition_table(\n        self, block_device: BlockDevice\n    ) -> PartitionTable:\n        raise NotImplementedError(\n            f\"Class '{FstabCommand.__name__}' does not implement the \"\n            f\"'{DeviceCommand._block_device_partition_table.__name__}' method!\"\n        )\n\n    def save_partition_table(self, partition_table: PartitionTable) -> None:\n        logger = self._logger\n        fstab_file_path = none_throws(partition_table.fstab_file_path)\n\n        try:\n            logger.info(f\"Modifying the '{fstab_file_path}' file.\")\n\n            with fileinput.input(str(fstab_file_path), inplace=True) as fstab_file:\n                for fstab_line in fstab_file:\n                    transformed_fstab_line = partition_table.transform_fstab_line(\n                        fstab_line\n                    )\n\n                    print(transformed_fstab_line, end=constants.EMPTY_STR)\n        except OSError as e:\n            logger.exception(\"fileinput.input() call failed!\")\n            raise PartitionError(\n                f\"Could not modify the '{fstab_file_path}' file!\"\n            ) from e\n\n    def _subvolume_partition_table(self, subvolume: Subvolume) -> PartitionTable:\n        filesystem_path = subvolume.filesystem_path\n        fstab_file_path = filesystem_path / constants.FSTAB_FILE\n\n        if not fstab_file_path.exists():\n            raise PartitionError(f\"The '{fstab_file_path}' file does not exist!\")\n\n        logger = self._logger\n        logical_path = subvolume.logical_path\n\n        try:\n            logger.info(\n                \"Initializing the static partition table for \"\n                f\"subvolume '{logical_path}' from its fstab file.\"\n            )\n\n            with fstab_file_path.open(\"r\") as fstab_file:\n                return (\n                    PartitionTable(constants.EMPTY_HEX_UUID, constants.FSTAB_PT_TYPE)\n                    .with_fstab_file_path(fstab_file_path)\n                    .with_partitions(FstabCommand._map_to_partitions(fstab_file))\n                )\n        except OSError as e:\n            logger.exception(\"Path.open('r') call failed!\")\n            raise PartitionError(\n                f\"Could not read from the '{fstab_file_path}' file!\"\n            ) from e\n\n    @staticmethod\n    def _map_to_partitions(\n        fstab_file: TextIO,\n    ) -> Iterator[Partition]:\n        for fstab_line in fstab_file:\n            if PartitionTable.is_valid_fstab_entry(fstab_line):\n                split_fstab_entry = fstab_line.split()\n                fs_dump = try_parse_int(split_fstab_entry[FstabColumn.FS_DUMP.value])\n                fs_fsck = try_parse_int(split_fstab_entry[FstabColumn.FS_FSCK.value])\n                filesystem = (\n                    Filesystem(\n                        constants.EMPTY_STR,\n                        constants.EMPTY_STR,\n                        split_fstab_entry[FstabColumn.FS_TYPE.value],\n                        split_fstab_entry[FstabColumn.FS_MOUNT_POINT.value],\n                    )\n                    .with_dump_and_fsck(\n                        default_if_none(fs_dump, 0),\n                        default_if_none(fs_fsck, 0),\n                    )\n                    .with_mount_options(\n                        split_fstab_entry[FstabColumn.FS_MOUNT_OPTIONS.value]\n                    )\n                )\n                partition = Partition(\n                    constants.EMPTY_STR,\n                    split_fstab_entry[FstabColumn.DEVICE_NAME.value],\n                    constants.EMPTY_STR,\n                ).with_filesystem(filesystem)\n\n                yield partition\n"
  },
  {
    "path": "src/refind_btrfs/system/lsblk_command.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport json\nimport subprocess\nfrom subprocess import CalledProcessError\nfrom typing import Any, Iterable, Iterator\n\nfrom more_itertools import always_iterable, one\n\nfrom refind_btrfs.common import ConfigurableMixin, constants\nfrom refind_btrfs.common.abc.commands import DeviceCommand\nfrom refind_btrfs.common.abc.factories import BaseLoggerFactory\nfrom refind_btrfs.common.abc.providers import BasePackageConfigProvider\nfrom refind_btrfs.common.enums import LsblkColumn, LsblkJsonKey\nfrom refind_btrfs.common.exceptions import PartitionError\nfrom refind_btrfs.device import (\n    BlockDevice,\n    Filesystem,\n    Partition,\n    PartitionTable,\n    Subvolume,\n)\nfrom refind_btrfs.utility.helpers import (\n    checked_cast,\n    default_if_none,\n    is_none_or_whitespace,\n)\n\n\nclass LsblkCommand(DeviceCommand, ConfigurableMixin):\n    def __init__(\n        self,\n        logger_factory: BaseLoggerFactory,\n        package_config_provider: BasePackageConfigProvider,\n    ) -> None:\n        ConfigurableMixin.__init__(self, package_config_provider)\n\n        self._logger = logger_factory.logger(__name__)\n\n    def get_block_devices(self) -> Iterator[BlockDevice]:\n        logger = self._logger\n        lsblk_columns = [\n            LsblkColumn.DEVICE_NAME,\n            LsblkColumn.DEVICE_TYPE,\n            LsblkColumn.MAJOR_MINOR,\n        ]\n        output = constants.COLUMN_SEPARATOR.join(\n            [lsblk_column_key.value.upper() for lsblk_column_key in lsblk_columns]\n        )\n        lsblk_command = f\"lsblk --json --merge --paths --output {output}\"\n\n        try:\n            logger.info(\"Initializing the block devices using lsblk.\")\n            logger.debug(f\"Running command '{lsblk_command}'.\")\n\n            lsblk_process = subprocess.run(\n                lsblk_command.split(), capture_output=True, check=True, text=True\n            )\n        except CalledProcessError as e:\n            stderr = checked_cast(str, e.stderr)\n\n            if is_none_or_whitespace(stderr):\n                message = \"lsblk execution failed!\"\n            else:\n                message = f\"lsblk execution failed: '{stderr.rstrip()}'!\"\n\n            logger.exception(message)\n            raise PartitionError(\"Could not initialize the block devices!\") from e\n\n        lsblk_parsed_output = json.loads(lsblk_process.stdout)\n        lsblk_blockdevices = always_iterable(\n            lsblk_parsed_output.get(LsblkJsonKey.BLOCKDEVICES.value)\n        )\n\n        yield from LsblkCommand._map_to_block_devices(lsblk_blockdevices)\n\n    # pylint: disable=unused-argument\n    def save_partition_table(self, partition_table: PartitionTable) -> None:\n        raise NotImplementedError(\n            f\"Class '{LsblkCommand.__name__}' does not implement the \"\n            f\"'{DeviceCommand.save_partition_table.__name__}' method!\"\n        )\n\n    def _block_device_partition_table(\n        self, block_device: BlockDevice\n    ) -> PartitionTable:\n        logger = self._logger\n        lsblk_columns = [\n            LsblkColumn.PTABLE_UUID,\n            LsblkColumn.PTABLE_TYPE,\n            LsblkColumn.PART_UUID,\n            LsblkColumn.PART_TYPE,\n            LsblkColumn.PART_LABEL,\n            LsblkColumn.FS_UUID,\n            LsblkColumn.DEVICE_NAME,\n            LsblkColumn.FS_TYPE,\n            LsblkColumn.FS_LABEL,\n            LsblkColumn.FS_MOUNT_POINT,\n        ]\n        device_name = block_device.name\n        output = constants.COLUMN_SEPARATOR.join(\n            [lsblk_column_key.value.upper() for lsblk_column_key in lsblk_columns]\n        )\n        lsblk_command = f\"lsblk {device_name} --json --paths --tree --output {output}\"\n\n        try:\n            logger.info(\n                f\"Initializing the physical partition table for device '{device_name}' using lsblk.\"\n            )\n            logger.debug(f\"Running command '{lsblk_command}'.\")\n\n            lsblk_process = subprocess.run(\n                lsblk_command.split(), check=True, capture_output=True, text=True\n            )\n        except CalledProcessError as e:\n            stderr = checked_cast(str, e.stderr)\n\n            if is_none_or_whitespace(stderr):\n                message = \"lsblk execution failed!\"\n            else:\n                message = f\"lsblk execution failed: '{stderr.rstrip()}'!\"\n\n            logger.exception(message)\n            raise PartitionError(\n                f\"Could not initialize the physical partition table for '{device_name}'!\"\n            ) from e\n\n        lsblk_parsed_output = json.loads(lsblk_process.stdout)\n        lsblk_blockdevice = one(\n            lsblk_parsed_output.get(LsblkJsonKey.BLOCKDEVICES.value)\n        )\n        lsblk_partition_table_columns = [\n            default_if_none(\n                lsblk_blockdevice.get(lsblk_column_key.value), constants.EMPTY_STR\n            )\n            for lsblk_column_key in [\n                LsblkColumn.PTABLE_UUID,\n                LsblkColumn.PTABLE_TYPE,\n            ]\n        ]\n        esp_uuid = self.package_config.esp_uuid\n        lsblk_partitions = always_iterable(\n            lsblk_blockdevice.get(LsblkJsonKey.CHILDREN.value)\n        )\n\n        return (\n            PartitionTable(*lsblk_partition_table_columns)\n            .with_esp_uuid(esp_uuid)\n            .with_partitions(LsblkCommand._map_to_partitions(lsblk_partitions))\n        )\n\n    def _subvolume_partition_table(self, subvolume: Subvolume) -> PartitionTable:\n        raise NotImplementedError(\n            f\"Class '{LsblkCommand.__name__}' does not implement the \"\n            f\"'{DeviceCommand._subvolume_partition_table.__name__}' method!\"\n        )\n\n    @staticmethod\n    def _map_to_block_devices(\n        lsblk_blockdevices: Iterable[Any],\n    ) -> Iterator[BlockDevice]:\n        for lsblk_blockdevice in lsblk_blockdevices:\n            lsblk_blockdevice_columns = [\n                default_if_none(\n                    lsblk_blockdevice.get(lsblk_column_key.value), constants.EMPTY_STR\n                )\n                for lsblk_column_key in [\n                    LsblkColumn.DEVICE_NAME,\n                    LsblkColumn.DEVICE_TYPE,\n                    LsblkColumn.MAJOR_MINOR,\n                ]\n            ]\n            lsblk_dependencies = always_iterable(\n                lsblk_blockdevice.get(LsblkJsonKey.CHILDREN.value)\n            )\n\n            yield (\n                BlockDevice(*lsblk_blockdevice_columns).with_dependencies(\n                    LsblkCommand._map_to_block_devices(lsblk_dependencies)\n                )\n            )\n\n    @staticmethod\n    def _map_to_partitions(\n        lsblk_partitions: Iterable[Any],\n    ) -> Iterator[Partition]:\n        for lsblk_partition in lsblk_partitions:\n            lsblk_part_columns = [\n                default_if_none(\n                    lsblk_partition.get(lsblk_column_key.value), constants.EMPTY_STR\n                )\n                for lsblk_column_key in [\n                    LsblkColumn.PART_UUID,\n                    LsblkColumn.DEVICE_NAME,\n                    LsblkColumn.PART_LABEL,\n                ]\n            ]\n            lsblk_fs_columns = [\n                default_if_none(\n                    lsblk_partition.get(lsblk_column_key.value), constants.EMPTY_STR\n                )\n                for lsblk_column_key in [\n                    LsblkColumn.FS_UUID,\n                    LsblkColumn.FS_LABEL,\n                    LsblkColumn.FS_TYPE,\n                    LsblkColumn.FS_MOUNT_POINT,\n                ]\n            ]\n\n            yield (\n                Partition(*lsblk_part_columns)\n                .with_part_type(\n                    default_if_none(\n                        lsblk_partition.get(LsblkColumn.PART_TYPE.value),\n                        constants.EMPTY_STR,\n                    )\n                )\n                .with_filesystem(Filesystem(*lsblk_fs_columns))\n            )\n\n            lsblk_nested_partitions = always_iterable(\n                lsblk_partition.get(LsblkJsonKey.CHILDREN.value)\n            )\n\n            yield from LsblkCommand._map_to_partitions(lsblk_nested_partitions)\n"
  },
  {
    "path": "src/refind_btrfs/system/pillow_command.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom pathlib import Path\nfrom typing import Callable, Set, Tuple, Union\n\nfrom refind_btrfs.common import BtrfsLogo, constants\nfrom refind_btrfs.common.abc.commands import IconCommand\nfrom refind_btrfs.common.abc.factories import BaseLoggerFactory\nfrom refind_btrfs.common.enums import (\n    BtrfsLogoHorizontalAlignment,\n    BtrfsLogoVerticalAlignment,\n)\nfrom refind_btrfs.common.exceptions import RefindConfigError\n\n\nclass PillowCommand(IconCommand):\n    def __init__(\n        self,\n        logger_factory: BaseLoggerFactory,\n    ) -> None:\n        minimum_offset: Callable[[int], int] = lambda _: 0\n        medium_offset: Callable[[int], int] = lambda delta: delta // 2\n        maximum_offset: Callable[[int], int] = lambda delta: delta\n\n        self._logger = logger_factory.logger(__name__)\n        self._validated_icons: Set[Path] = set()\n        self._embed_offset_initializers: dict[\n            Union[BtrfsLogoHorizontalAlignment, BtrfsLogoVerticalAlignment],\n            Callable[[int], int],\n        ] = {\n            BtrfsLogoHorizontalAlignment.LEFT: minimum_offset,\n            BtrfsLogoHorizontalAlignment.CENTER: medium_offset,\n            BtrfsLogoHorizontalAlignment.RIGHT: maximum_offset,\n            BtrfsLogoVerticalAlignment.TOP: minimum_offset,\n            BtrfsLogoVerticalAlignment.CENTER: medium_offset,\n            BtrfsLogoVerticalAlignment.BOTTOM: maximum_offset,\n        }\n\n    def validate_custom_icon(\n        self, refind_config_path: Path, source_icon_path: Path, custom_icon_path: Path\n    ) -> Path:\n        custom_icon_absolute_path = refind_config_path.parent / custom_icon_path\n\n        if not custom_icon_absolute_path.exists():\n            raise RefindConfigError(\n                f\"The '{custom_icon_absolute_path}' path does not exist!\"\n            )\n\n        validated_icons = self._validated_icons\n\n        if custom_icon_absolute_path not in validated_icons:\n            refind_directory = refind_config_path.parent\n            logger = self._logger\n\n            try:\n                # pylint: disable=import-outside-toplevel\n                from PIL import Image\n\n                logger.info(\n                    \"Validating the \"\n                    f\"'{custom_icon_absolute_path.relative_to(refind_directory)}' file.\"\n                )\n\n                with Image.open(custom_icon_absolute_path, \"r\") as custom_icon_image:\n                    expected_formats = [\"PNG\", \"JPEG\", \"BMP\", \"ICNS\"]\n                    custom_icon_image_format = custom_icon_image.format\n\n                    if custom_icon_image_format not in expected_formats:\n                        raise RefindConfigError(\n                            f\"The '{custom_icon_absolute_path.name}' image's \"\n                            f\"format ('{custom_icon_image_format}') is not supported!\"\n                        )\n            except OSError as e:\n                logger.exception(\"Image.open('r') call failed!\")\n                raise RefindConfigError(\n                    f\"Could not read the '{custom_icon_absolute_path}' file!\"\n                ) from e\n\n            validated_icons.add(custom_icon_absolute_path)\n\n        return PillowCommand._discern_destination_icon_relative_path(\n            refind_config_path, source_icon_path, custom_icon_absolute_path\n        )\n\n    def embed_btrfs_logo_into_source_icon(\n        self, refind_config_path: Path, source_icon_path: Path, btrfs_logo: BtrfsLogo\n    ) -> Path:\n        source_icon_absolute_path = PillowCommand._discern_source_icon_absolute_path(\n            refind_config_path, source_icon_path\n        )\n        absolute_paths = PillowCommand._discern_absolute_paths_for_btrfs_logo_embedding(\n            refind_config_path, source_icon_absolute_path, btrfs_logo\n        )\n        btrfs_logo_absolute_path = absolute_paths[0]\n        destination_icon_absolute_path = absolute_paths[1]\n\n        if not destination_icon_absolute_path.exists():\n            logger = self._logger\n            refind_directory = refind_config_path.parent\n\n            try:\n                # pylint: disable=import-outside-toplevel\n                from PIL import Image\n\n                logger.info(\n                    \"Embedding \"\n                    f\"the '{btrfs_logo_absolute_path.name}' \"\n                    \"logo into \"\n                    f\"the '{source_icon_absolute_path.relative_to(refind_directory)}' icon.\"\n                )\n\n                with Image.open(\n                    btrfs_logo_absolute_path\n                ) as btrfs_logo_image, Image.open(\n                    source_icon_absolute_path\n                ) as source_icon_image:\n                    expected_format = \"PNG\"\n                    source_icon_image_format = source_icon_image.format\n\n                    if source_icon_image_format != expected_format:\n                        raise RefindConfigError(\n                            f\"The '{source_icon_absolute_path.name}' image's \"\n                            f\"format ('{source_icon_image_format}') is not supported!\"\n                        )\n\n                    btrfs_logo_image_width = btrfs_logo_image.width\n                    source_icon_image_width = source_icon_image.width\n\n                    if source_icon_image_width < btrfs_logo_image_width:\n                        raise RefindConfigError(\n                            f\"The '{source_icon_absolute_path.name}' image's width \"\n                            f\"({source_icon_image_width} px) is less than \"\n                            \"the selected Btrfs logo's width!\"\n                        )\n\n                    btrfs_logo_image_height = btrfs_logo_image.height\n                    source_icon_image_height = source_icon_image.height\n\n                    if source_icon_image_height < btrfs_logo_image_height:\n                        raise RefindConfigError(\n                            f\"The '{source_icon_absolute_path.name}' image's height \"\n                            f\"({source_icon_image_height} px) is less than \"\n                            \"the selected Btrfs logo's height!\"\n                        )\n\n                    try:\n                        horizontal_alignment = btrfs_logo.horizontal_alignment\n                        x_delta = source_icon_image_width - btrfs_logo_image_width\n                        x_offset = self._embed_offset_initializers[\n                            horizontal_alignment\n                        ](x_delta)\n                        vertical_alignment = btrfs_logo.vertical_alignment\n                        y_delta = source_icon_image_height - btrfs_logo_image_height\n                        y_offset = self._embed_offset_initializers[vertical_alignment](\n                            y_delta\n                        )\n                        resized_btrfs_logo_image = Image.new(\n                            btrfs_logo_image.mode, source_icon_image.size\n                        )\n\n                        resized_btrfs_logo_image.paste(\n                            btrfs_logo_image,\n                            (\n                                x_offset,\n                                y_offset,\n                            ),\n                        )\n\n                        destination_icon_image = Image.alpha_composite(\n                            source_icon_image, resized_btrfs_logo_image\n                        )\n                        destination_directory = (\n                            refind_directory\n                            / constants.SNAPSHOT_STANZAS_DIR_NAME\n                            / constants.ICONS_DIR\n                        )\n\n                        if not destination_directory.exists():\n                            logger.info(\n                                \"Creating the \"\n                                f\"'{destination_directory.relative_to(refind_directory)}' \"\n                                \"destination directory.\"\n                            )\n\n                            destination_directory.mkdir(parents=True)\n\n                        logger.info(\n                            \"Saving the \"\n                            f\"'{destination_icon_absolute_path.relative_to(refind_directory)}' \"\n                            \"file.\"\n                        )\n\n                        destination_icon_image.save(destination_icon_absolute_path)\n                    except OSError as e:\n                        logger.exception(\"Image.save() call failed!\")\n                        raise RefindConfigError(\n                            f\"Could not save the '{e.filename}' file!\"\n                        ) from e\n\n            except OSError as e:\n                logger.exception(\"Image.open('r') call failed!\")\n                raise RefindConfigError(\n                    f\"Could not read the '{e.filename}' file!\"\n                ) from e\n\n        return PillowCommand._discern_destination_icon_relative_path(\n            refind_config_path, source_icon_path, destination_icon_absolute_path\n        )\n\n    @staticmethod\n    def _discern_source_icon_absolute_path(\n        refind_config_path: Path, icon_path: Path\n    ) -> Path:\n        refind_config_path_parents = refind_config_path.parents\n        icon_path_parts = icon_path.parts\n\n        for parent in refind_config_path_parents:\n            if parent.name not in icon_path_parts:\n                return parent / str(icon_path).removeprefix(constants.FORWARD_SLASH)\n\n        raise RefindConfigError(\n            f\"Could not discern the '{icon_path.name}' file's absolute path!\"\n        )\n\n    @staticmethod\n    def _discern_destination_icon_relative_path(\n        refind_config_path: Path,\n        source_icon_path: Path,\n        destination_icon_path: Path,\n    ) -> Path:\n        source_icon_path_parts = source_icon_path.parts\n        refind_config_path_parents = refind_config_path.parents\n\n        for parent in refind_config_path_parents:\n            if parent.name not in source_icon_path_parts:\n                return constants.ROOT_DIR / destination_icon_path.relative_to(parent)\n\n        raise RefindConfigError(\n            f\"Could not discern the '{destination_icon_path.name}' file's relative path!\"\n        )\n\n    @staticmethod\n    def _discern_absolute_paths_for_btrfs_logo_embedding(\n        refind_config_path: Path, source_icon_absolute_path: Path, btrfs_logo: BtrfsLogo\n    ) -> Tuple[Path, Path]:\n        variant = btrfs_logo.variant\n        size = btrfs_logo.size\n        horizontal_alignment = btrfs_logo.horizontal_alignment\n        vertical_alignment = btrfs_logo.vertical_alignment\n        btrfs_logos_directory = constants.BTRFS_LOGOS_DIR\n        btrfs_logo_name = f\"{variant.value}_{size.value}.png\"\n        btrfs_logo_absolute_path = btrfs_logos_directory / btrfs_logo_name\n        refind_directory = refind_config_path.parent\n        destination_directory = (\n            refind_directory / constants.SNAPSHOT_STANZAS_DIR_NAME / constants.ICONS_DIR\n        )\n        destination_icon_name = (\n            f\"{source_icon_absolute_path.stem}_{btrfs_logo_absolute_path.stem}_\"\n            f\"h-{horizontal_alignment.value}_v-{vertical_alignment.value}.png\"\n        )\n        destination_icon_absolute_path = destination_directory / destination_icon_name\n\n        return (btrfs_logo_absolute_path, destination_icon_absolute_path)\n"
  },
  {
    "path": "src/refind_btrfs/utility/__init__.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom .level_aware_formatter import LevelAwareFormatter\n"
  },
  {
    "path": "src/refind_btrfs/utility/file_package_config_provider.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport sys\nfrom datetime import datetime\nfrom importlib.util import find_spec\nfrom pathlib import Path\nfrom typing import Any, Callable, Iterator, Optional, Type, TypeVar, cast\nfrom uuid import UUID\n\nfrom injector import inject\nfrom more_itertools import one, unique_everseen\nfrom tomlkit.exceptions import TOMLKitError\nfrom tomlkit.items import AoT, Table\nfrom tomlkit.toml_document import TOMLDocument\nfrom tomlkit.toml_file import TOMLFile\n\nfrom refind_btrfs.common import (\n    BootStanzaGeneration,\n    BtrfsLogo,\n    Icon,\n    PackageConfig,\n    SnapshotManipulation,\n    SnapshotSearch,\n    constants,\n)\nfrom refind_btrfs.common.abc.factories import BaseLoggerFactory\nfrom refind_btrfs.common.abc.providers import (\n    BasePackageConfigProvider,\n    BasePersistenceProvider,\n)\nfrom refind_btrfs.common.enums import (\n    BootStanzaGenerationConfigKey,\n    BootStanzaIconGenerationMode,\n    BtrfsLogoConfigKey,\n    BtrfsLogoHorizontalAlignment,\n    BtrfsLogoSize,\n    BtrfsLogoVariant,\n    BtrfsLogoVerticalAlignment,\n    ConfigInitializationType,\n    IconConfigKey,\n    PathRelation,\n    SnapshotManipulationConfigKey,\n    SnapshotSearchConfigKey,\n    TopLevelConfigKey,\n)\nfrom refind_btrfs.common.exceptions import PackageConfigError\nfrom refind_btrfs.device import NumIdRelation, Subvolume, UuidRelation\n\nfrom .helpers import (\n    checked_cast,\n    discern_path_relation_of,\n    has_items,\n    none_throws,\n    try_convert_str_to_enum,\n    try_parse_uuid,\n)\n\nTSourceValue = TypeVar(\"TSourceValue\")\nTDestinationValue = TypeVar(\"TDestinationValue\")\n\n\nclass FilePackageConfigProvider(BasePackageConfigProvider):\n    default_package_config = PackageConfig(\n        constants.EMPTY_UUID,\n        True,\n        True,\n        [SnapshotSearch(Path(\"/.snapshots\"), False, 2)],\n        SnapshotManipulation(5, False, Path(\"/root/.refind-btrfs\"), set()),\n        BootStanzaGeneration(\n            \"refind.conf\",\n            True,\n            False,\n            set(),\n            Icon(\n                BootStanzaIconGenerationMode.DEFAULT,\n                Path(\"btrfs-snapshot-stanzas/icons/sample_icon.png\"),\n                BtrfsLogo(\n                    BtrfsLogoVariant.ORIGINAL,\n                    BtrfsLogoSize.MEDIUM,\n                    BtrfsLogoHorizontalAlignment.CENTER,\n                    BtrfsLogoVerticalAlignment.CENTER,\n                ),\n            ),\n        ),\n    )\n\n    @inject\n    def __init__(\n        self,\n        logger_factory: BaseLoggerFactory,\n        persistence_provider: BasePersistenceProvider,\n    ) -> None:\n        self._logger = logger_factory.logger(__name__)\n        self._persistence_provider = persistence_provider\n        self._package_config: Optional[PackageConfig] = None\n\n    def get_config(self) -> PackageConfig:\n        persistence_provider = self._persistence_provider\n        persisted_package_config = persistence_provider.get_package_config()\n        current_package_config = self._package_config\n\n        if persisted_package_config is None:\n            logger = self._logger\n            config_file_path = constants.PACKAGE_CONFIG_FILE\n\n            if not config_file_path.exists():\n                raise PackageConfigError(\n                    f\"The '{config_file_path}' path does not exist!\"\n                )\n\n            if not config_file_path.is_file():\n                raise PackageConfigError(\n                    f\"The '{config_file_path}' does not represent a file!\"\n                )\n\n            logger.info(f\"Analyzing the '{config_file_path.name}' file.\")\n\n            try:\n                toml_file = TOMLFile(str(config_file_path))\n                toml_document = toml_file.read()\n            except TOMLKitError as e:\n                logger.exception(\n                    f\"Error while parsing the '{config_file_path.name}' file\"\n                )\n                raise PackageConfigError(\n                    \"Could not load the package configuration from file'!\"\n                ) from e\n            else:\n                current_package_config = FilePackageConfigProvider._read_config_from(\n                    toml_document\n                ).with_initialization_type(ConfigInitializationType.PARSED)\n\n                persistence_provider.save_package_config(\n                    none_throws(current_package_config)\n                )\n        elif current_package_config is None:\n            current_package_config = persisted_package_config.with_initialization_type(\n                ConfigInitializationType.PERSISTED\n            )\n\n        self._package_config = current_package_config\n\n        return none_throws(current_package_config)\n\n    @staticmethod\n    def _read_config_from(toml_document: TOMLDocument):\n        container = cast(dict, toml_document)\n        default_package_config = FilePackageConfigProvider.default_package_config\n        esp_uuid = FilePackageConfigProvider._get_config_value(\n            container,\n            TopLevelConfigKey.ESP_UUID.value,\n            str,\n            default_package_config,\n            (UUID, try_parse_uuid),\n        )\n        exit_if_root_is_snapshot = FilePackageConfigProvider._get_config_value(\n            container,\n            TopLevelConfigKey.EXIT_IF_ROOT_IS_SNAPSHOT.value,\n            bool,\n            default_package_config,\n        )\n        exit_if_no_changes_are_detected = FilePackageConfigProvider._get_config_value(\n            container,\n            TopLevelConfigKey.EXIT_IF_NO_CHANGES_ARE_DETECTED.value,\n            bool,\n            default_package_config,\n        )\n        snapshot_searches_key = TopLevelConfigKey.SNAPSHOT_SEARCH.value\n        default_snapshot_searches = default_package_config.snapshot_searches\n\n        if snapshot_searches_key in container:\n            snapshot_searches = list(\n                unique_everseen(\n                    FilePackageConfigProvider._map_to_snapshot_searches(\n                        checked_cast(AoT, container[snapshot_searches_key]),\n                        one(default_snapshot_searches),\n                    )\n                )\n            )\n        else:\n            snapshot_searches = default_snapshot_searches\n\n        snapshot_manipulation_key = TopLevelConfigKey.SNAPSHOT_MANIPULATION.value\n\n        if snapshot_manipulation_key in container:\n            snapshot_manipulation = (\n                FilePackageConfigProvider._map_to_snapshot_manipulation(\n                    checked_cast(\n                        Table,\n                        container[snapshot_manipulation_key],\n                    ),\n                    default_package_config.snapshot_manipulation,\n                )\n            )\n        else:\n            snapshot_manipulation = default_package_config.snapshot_manipulation\n\n        destination_directory = snapshot_manipulation.destination_directory\n\n        for snapshot_search in snapshot_searches:\n            search_directory = snapshot_search.directory\n            path_relation = discern_path_relation_of(\n                (destination_directory, search_directory)\n            )\n\n            if path_relation == PathRelation.SAME:\n                raise PackageConfigError(\n                    \"The search and destination directories cannot be the same!\"\n                )\n\n            if path_relation == PathRelation.FIRST_NESTED_IN_SECOND:\n                raise PackageConfigError(\n                    f\"The '{destination_directory}' destination directory is nested in \"\n                    f\"the '{search_directory}' search directory!\"\n                )\n\n            if path_relation == PathRelation.SECOND_NESTED_IN_FIRST:\n                raise PackageConfigError(\n                    f\"The '{search_directory}' search directory is nested in \"\n                    f\"the '{destination_directory}' destination directory!\"\n                )\n\n        boot_stanza_generation_key = TopLevelConfigKey.BOOT_STANZA_GENERATION.value\n\n        if boot_stanza_generation_key in container:\n            boot_stanza_generation = (\n                FilePackageConfigProvider._map_to_boot_stanza_generation(\n                    checked_cast(Table, container[boot_stanza_generation_key]),\n                    default_package_config.boot_stanza_generation,\n                )\n            )\n        else:\n            boot_stanza_generation = default_package_config.boot_stanza_generation\n\n        return PackageConfig(\n            esp_uuid,\n            exit_if_root_is_snapshot,\n            exit_if_no_changes_are_detected,\n            snapshot_searches,\n            snapshot_manipulation,\n            boot_stanza_generation,\n        )\n\n    @staticmethod\n    def _map_to_snapshot_searches(\n        snapshot_search_values: AoT, default_snapshot_search: SnapshotSearch\n    ) -> Iterator[SnapshotSearch]:\n        max_depth_key = SnapshotSearchConfigKey.MAX_DEPTH.value\n\n        for snapshot_search_value in snapshot_search_values.body:\n            container = cast(dict, snapshot_search_value)\n            directory = cast(\n                Path,\n                FilePackageConfigProvider._get_config_value(\n                    container,\n                    SnapshotSearchConfigKey.DIRECTORY.value,\n                    str,\n                    default_snapshot_search,\n                    (Path, None),\n                ),\n            )\n\n            if not directory.exists():\n                raise PackageConfigError(f\"The '{directory}' path does not exist!\")\n\n            if not directory.is_dir():\n                raise PackageConfigError(\n                    f\"The '{directory}' path does not represent a directory!\"\n                )\n\n            is_nested = FilePackageConfigProvider._get_config_value(\n                container,\n                SnapshotSearchConfigKey.IS_NESTED.value,\n                bool,\n                default_snapshot_search,\n            )\n            max_depth = cast(\n                int,\n                FilePackageConfigProvider._get_config_value(\n                    container, max_depth_key, int, default_snapshot_search\n                ),\n            )\n\n            if max_depth <= 0:\n                raise PackageConfigError(\n                    f\"The '{max_depth_key}' option must be greater than zero!\"\n                )\n\n            yield SnapshotSearch(directory, is_nested, max_depth)\n\n    @staticmethod\n    def _map_to_snapshot_manipulation(\n        snapshot_manipulation_value: Table,\n        default_snapshot_manipulation: SnapshotManipulation,\n    ) -> SnapshotManipulation:\n        container = cast(dict, snapshot_manipulation_value)\n        selection_count_key = SnapshotManipulationConfigKey.SELECTION_COUNT.value\n\n        if selection_count_key in container:\n            selection_count_value = container[selection_count_key]\n\n            if isinstance(selection_count_value, int):\n                selection_count = int(selection_count_value)\n\n                if selection_count <= 0:\n                    raise PackageConfigError(\n                        f\"The '{selection_count_key}' option must be greater than zero!\"\n                    )\n            elif isinstance(selection_count_value, str):\n                actual_string = str(selection_count_value).strip()\n                expected_string = constants.SNAPSHOT_SELECTION_COUNT_INFINITY\n\n                if actual_string != expected_string:\n                    raise PackageConfigError(\n                        f\"In case the '{selection_count_key}' option is a string \"\n                        f\"it can only be set to '{expected_string}'!\"\n                    )\n\n                selection_count = sys.maxsize\n            else:\n                raise PackageConfigError(\n                    f\"The '{selection_count_key}' option must be either an integer or a string!\"\n                )\n        else:\n            selection_count = default_snapshot_manipulation.selection_count\n\n        modify_read_only_flag = FilePackageConfigProvider._get_config_value(\n            container,\n            SnapshotManipulationConfigKey.MODIFY_READ_ONLY_FLAG.value,\n            bool,\n            default_snapshot_manipulation,\n        )\n        destination_directory = FilePackageConfigProvider._get_config_value(\n            container,\n            SnapshotManipulationConfigKey.DESTINATION_DIRECTORY.value,\n            str,\n            default_snapshot_manipulation,\n            (Path, None),\n        )\n        cleanup_exclusion_key = SnapshotManipulationConfigKey.CLEANUP_EXCLUSION.value\n        cleanup_exclusion = cast(\n            list,\n            FilePackageConfigProvider._get_config_value(\n                container,\n                cleanup_exclusion_key,\n                list,\n                default_snapshot_manipulation,\n            ),\n        )\n        uuids: list[UUID] = []\n\n        if has_items(cleanup_exclusion):\n            for item in cleanup_exclusion:\n                if not isinstance(item, str):\n                    raise PackageConfigError(\n                        f\"Every member of the '{cleanup_exclusion_key}' array must be a string!\"\n                    )\n\n                uuid = try_parse_uuid(item)\n                type_name = UUID.__name__\n\n                if uuid is None:\n                    raise PackageConfigError(\n                        f\"Could not convert '{item}' to expected type ('{type_name}')!\"\n                    )\n\n                if uuid == constants.EMPTY_UUID:\n                    raise PackageConfigError(\n                        f\"The '{cleanup_exclusion_key}' array must \"\n                        f\"not contain empty '{type_name}' values!\"\n                    )\n\n                uuids.append(uuid)\n\n        return SnapshotManipulation(\n            selection_count,\n            modify_read_only_flag,\n            destination_directory,\n            set(\n                Subvolume(\n                    constants.EMPTY_PATH,\n                    constants.EMPTY_STR,\n                    datetime.min,\n                    UuidRelation(uuid, constants.EMPTY_UUID),\n                    NumIdRelation(0, 0),\n                    False,\n                )\n                for uuid in uuids\n            ),\n        )\n\n    @staticmethod\n    def _map_to_boot_stanza_generation(\n        boot_stanza_generation_value: Table,\n        default_boot_stanza_generation: BootStanzaGeneration,\n    ) -> BootStanzaGeneration:\n        container = cast(dict, boot_stanza_generation_value)\n        refind_config = FilePackageConfigProvider._get_config_value(\n            container,\n            BootStanzaGenerationConfigKey.REFIND_CONFIG.value,\n            str,\n            default_boot_stanza_generation,\n        )\n        include_paths = FilePackageConfigProvider._get_config_value(\n            container,\n            BootStanzaGenerationConfigKey.INCLUDE_PATHS.value,\n            bool,\n            default_boot_stanza_generation,\n        )\n        include_sub_menus = FilePackageConfigProvider._get_config_value(\n            container,\n            BootStanzaGenerationConfigKey.INCLUDE_SUB_MENUS.value,\n            bool,\n            default_boot_stanza_generation,\n        )\n        source_exclusion_key = BootStanzaGenerationConfigKey.SOURCE_EXCLUSION.value\n        source_exclusion = cast(\n            list,\n            FilePackageConfigProvider._get_config_value(\n                container,\n                source_exclusion_key,\n                list,\n                default_boot_stanza_generation,\n            ),\n        )\n\n        if has_items(source_exclusion):\n            for item in source_exclusion:\n                if not isinstance(item, str):\n                    raise PackageConfigError(\n                        f\"Every member of the '{source_exclusion_key}' array must be a string!\"\n                    )\n\n        icon_key = BootStanzaGenerationConfigKey.ICON.value\n\n        if icon_key in container:\n            icon = FilePackageConfigProvider._map_to_icon(\n                checked_cast(Table, container[icon_key]),\n                default_boot_stanza_generation.icon,\n            )\n        else:\n            icon = default_boot_stanza_generation.icon\n\n        return BootStanzaGeneration(\n            refind_config,\n            include_paths,\n            include_sub_menus,\n            set(cast(str, loader_filename) for loader_filename in source_exclusion),\n            icon,\n        )\n\n    @staticmethod\n    def _map_to_icon(icon_value: Table, default_icon: Icon) -> Icon:\n        container = cast(dict, icon_value)\n        mode = FilePackageConfigProvider._get_config_value(\n            container,\n            IconConfigKey.MODE.value,\n            str,\n            default_icon,\n            (\n                BootStanzaIconGenerationMode,\n                lambda value: try_convert_str_to_enum(\n                    value, BootStanzaIconGenerationMode\n                ),\n            ),\n        )\n\n        if mode != BootStanzaIconGenerationMode.DEFAULT:\n            pil_spec = find_spec(\"PIL\")\n\n            if pil_spec is None:\n                raise PackageConfigError(\n                    f\"The '{mode.value}' mode of boot stanza icon \"\n                    \"generation requires that the 'Pillow' package is installed!\"\n                )\n\n        path = FilePackageConfigProvider._get_config_value(\n            container,\n            IconConfigKey.PATH.value,\n            str,\n            default_icon,\n            (Path, None),\n        )\n\n        btrfs_logo_key = IconConfigKey.BTRFS_LOGO.value\n\n        if btrfs_logo_key in container:\n            btrfs_logo = FilePackageConfigProvider._map_to_btrfs_logo(\n                checked_cast(Table, container[btrfs_logo_key]),\n                default_icon.btrfs_logo,\n            )\n        else:\n            btrfs_logo = default_icon.btrfs_logo\n\n        return Icon(mode, path, btrfs_logo)\n\n    @staticmethod\n    def _map_to_btrfs_logo(\n        btrfs_logo_value: Table, default_btrfs_logo: BtrfsLogo\n    ) -> BtrfsLogo:\n        container = cast(dict, btrfs_logo_value)\n        variant = FilePackageConfigProvider._get_config_value(\n            container,\n            BtrfsLogoConfigKey.VARIANT.value,\n            str,\n            default_btrfs_logo,\n            (\n                BtrfsLogoVariant,\n                lambda value: try_convert_str_to_enum(value, BtrfsLogoVariant),\n            ),\n        )\n        size = FilePackageConfigProvider._get_config_value(\n            container,\n            BtrfsLogoConfigKey.SIZE.value,\n            str,\n            default_btrfs_logo,\n            (\n                BtrfsLogoSize,\n                lambda value: try_convert_str_to_enum(value, BtrfsLogoSize),\n            ),\n        )\n        horizontal_alignment = FilePackageConfigProvider._get_config_value(\n            container,\n            BtrfsLogoConfigKey.HORIZONTAL_ALIGNMENT.value,\n            str,\n            default_btrfs_logo,\n            (\n                BtrfsLogoHorizontalAlignment,\n                lambda value: try_convert_str_to_enum(\n                    value, BtrfsLogoHorizontalAlignment\n                ),\n            ),\n        )\n        vertical_alignment = FilePackageConfigProvider._get_config_value(\n            container,\n            BtrfsLogoConfigKey.VERTICAL_ALIGNMENT.value,\n            str,\n            default_btrfs_logo,\n            (\n                BtrfsLogoVerticalAlignment,\n                lambda value: try_convert_str_to_enum(\n                    value, BtrfsLogoVerticalAlignment\n                ),\n            ),\n        )\n\n        return BtrfsLogo(variant, size, horizontal_alignment, vertical_alignment)\n\n    @staticmethod\n    def _get_config_value(\n        container: dict,\n        key: str,\n        source_type: Type[TSourceValue],\n        default_config: object,\n        value_conversion: Optional[\n            tuple[Type[TDestinationValue], Optional[Callable[[TSourceValue], Any]]]\n        ] = None,\n    ) -> Any:\n        if key in container:\n            source_value = container[key]\n\n            if not isinstance(source_value, source_type):\n                raise PackageConfigError(\n                    f\"The '{key}' option must be of type '{source_type.__name__}'!\"\n                )\n\n            if value_conversion is not None:\n                destination_type = value_conversion[0]\n                converter_func = value_conversion[1]\n\n                if converter_func is None:\n                    converter_func = cast(\n                        Callable[[TSourceValue], Any], destination_type\n                    )\n\n                destination_value = converter_func(source_value)\n\n                if destination_value is None:\n                    raise PackageConfigError(\n                        f\"Could not convert '{source_value}' to \"\n                        f\"expected type ('{destination_type.__name__}')!\"\n                    )\n\n                return checked_cast(destination_type, destination_value)\n\n            return checked_cast(source_type, source_value)\n\n        return getattr(default_config, key)\n"
  },
  {
    "path": "src/refind_btrfs/utility/helpers.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport errno\nimport os\nimport re\nfrom enum import Enum\nfrom inspect import ismethod\nfrom pathlib import Path\nfrom typing import Any, Iterator, Optional, Sized, Type, TypeVar, cast\nfrom uuid import UUID\n\nfrom more_itertools import first\nfrom typeguard import check_type\n\nfrom refind_btrfs.common import constants\nfrom refind_btrfs.common.enums import PathRelation\n\n\nTParam = TypeVar(\"TParam\")\n\n\ndef check_access_rights() -> None:\n    if os.getuid() != constants.ROOT_UID:\n        error_code = errno.EPERM\n\n        raise PermissionError(error_code, os.strerror(error_code))\n\n\ndef try_parse_int(value: str, base: int = 10) -> Optional[int]:\n    try:\n        return int(value, base)\n    except ValueError:\n        return None\n\n\ndef try_parse_uuid(value: str) -> Optional[UUID]:\n    try:\n        return UUID(hex=value)\n    except ValueError:\n        return None\n\n\ndef try_convert_str_to_enum(value: str, enum_type: Type[Enum]) -> Optional[Enum]:\n    upper_value = value.upper()\n    member_names = [member.name for member in enum_type]\n\n    if upper_value in member_names:\n        return enum_type[upper_value]\n\n    return None\n\n\ndef try_convert_bytes_to_uuid(value: bytes) -> Optional[UUID]:\n    try:\n        return UUID(bytes=value)\n    except ValueError:\n        return None\n\n\ndef is_empty(value: Optional[str]) -> bool:\n    if value is None:\n        return False\n\n    return value == constants.EMPTY_STR\n\n\ndef is_none_or_whitespace(value: Optional[str]) -> bool:\n    if value is None:\n        return True\n\n    return is_empty(value) or value.isspace()\n\n\ndef strip_quotes(value: Optional[str]) -> str:\n    if not is_none_or_whitespace(value):\n        return (\n            none_throws(value)\n            .strip(constants.SINGLE_QUOTE)\n            .strip(constants.DOUBLE_QUOTE)\n        )\n\n    return constants.EMPTY_STR\n\n\ndef has_method(obj: Any, method_name: str) -> bool:\n    if hasattr(obj, method_name):\n        attr = getattr(obj, method_name)\n\n        return ismethod(attr)\n\n    return False\n\n\ndef has_items(value: Optional[Sized]) -> bool:\n    return value is not None and len(value) > 0\n\n\ndef is_singleton(value: Optional[Sized]) -> bool:\n    return value is not None and len(value) == 1\n\n\ndef item_count_suffix(value: Sized) -> str:\n    assert has_items(\n        value\n    ), \"The 'value' parameter must be initialized and contain least one item!\"\n\n    return constants.EMPTY_STR if is_singleton(value) else \"s\"\n\n\ndef find_all_matched_files_in(root_directory: Path, filename: str) -> Iterator[Path]:\n    if root_directory.exists() and root_directory.is_dir():\n        children = root_directory.iterdir()\n\n        for child in children:\n            if child.is_file():\n                if child.name == filename:\n                    yield child\n            elif child.is_dir():\n                yield from find_all_matched_files_in(child, filename)\n\n\ndef find_all_directories_in(\n    root_directory: Path, max_depth: int, current_depth: int = 0\n) -> Iterator[Path]:\n    if current_depth > max_depth:\n        return\n\n    if root_directory.exists() and root_directory.is_dir():\n        yield root_directory.resolve()\n\n        subdirectories = (child for child in root_directory.iterdir() if child.is_dir())\n\n        for subdirectory in subdirectories:\n            yield from find_all_directories_in(\n                subdirectory, max_depth, current_depth + 1\n            )\n\n\ndef discern_path_relation_of(path_pair: tuple[Path, Path]) -> PathRelation:\n    first_resolved = path_pair[0].resolve()\n    second_resolved = path_pair[1].resolve()\n\n    if first_resolved == second_resolved:\n        return PathRelation.SAME\n\n    first_parents = first_resolved.parents\n\n    if second_resolved in first_parents:\n        return PathRelation.FIRST_NESTED_IN_SECOND\n\n    second_parents = second_resolved.parents\n\n    if first_resolved in second_parents:\n        return PathRelation.SECOND_NESTED_IN_FIRST\n\n    return PathRelation.UNRELATED\n\n\ndef discern_distance_between(path_pair: tuple[Path, Path]) -> Optional[int]:\n    path_relation = discern_path_relation_of(path_pair)\n\n    if path_relation != PathRelation.UNRELATED:\n        distance = 0\n\n        if path_relation != PathRelation.SAME:\n            if path_relation == PathRelation.FIRST_NESTED_IN_SECOND:\n                first_parts = path_pair[0].parts\n                second_stem = path_pair[1].stem\n\n                for part in reversed(first_parts):\n                    if part != second_stem:\n                        distance += 1\n                    else:\n                        break\n            elif path_relation == PathRelation.SECOND_NESTED_IN_FIRST:\n                first_stem = path_pair[0].stem\n                second_parts = path_pair[1].parts\n\n                for part in reversed(second_parts):\n                    if part != first_stem:\n                        distance += 1\n                    else:\n                        break\n\n        return distance\n\n    return None\n\n\ndef normalize_dir_separators_in(\n    path: str,\n    separator_replacement: tuple[\n        str, str\n    ] = constants.DEFAULT_DIR_SEPARATOR_REPLACEMENT,\n) -> str:\n    path_with_replaced_separators = path.replace(*separator_replacement)\n    pattern = re.compile(rf\"(?P<prefix>^({constants.DIR_SEPARATOR_PATTERN}){{2,}})\")\n    match = pattern.match(path_with_replaced_separators)\n\n    if match:\n        prefix = match.group(\"prefix\")\n        path_with_replaced_separators = path_with_replaced_separators.removeprefix(\n            first(prefix) * (len(prefix) - 1)\n        )\n\n    return path_with_replaced_separators\n\n\ndef replace_root_part_in(\n    full_path: str,\n    current_root_part: str,\n    replacement_root_part: str,\n    separator_replacement: tuple[\n        str, str\n    ] = constants.DEFAULT_DIR_SEPARATOR_REPLACEMENT,\n) -> str:\n    pattern = re.compile(\n        rf\"(?P<prefix>^{constants.DIR_SEPARATOR_PATTERN}?)\"\n        f\"{current_root_part}\"\n        rf\"(?P<suffix>{constants.DIR_SEPARATOR_PATTERN})\"\n    )\n    substituted_full_path = pattern.sub(\n        rf\"\\g<prefix>{replacement_root_part}\\g<suffix>\", full_path\n    )\n\n    return normalize_dir_separators_in(substituted_full_path, separator_replacement)\n\n\ndef replace_item_in(\n    items_list: list[TParam], current: TParam, replacement: Optional[TParam] = None\n) -> None:\n    if not has_items(items_list):\n        return\n\n    if current in items_list:\n        index = items_list.index(current)\n\n        if replacement is None:\n            replacement = current\n\n        items_list[index] = replacement\n\n\ndef none_throws(value: Optional[TParam], message: str = \"Unexpected 'None'\") -> TParam:\n    if value is None:\n        raise AssertionError(message)\n\n    return value\n\n\ndef default_if_none(value: Optional[TParam], default: TParam) -> TParam:\n    if value is None:\n        return default\n\n    return value\n\n\ndef checked_cast(destination_type: Type[TParam], value: Any) -> TParam:\n    check_type(value, destination_type)\n\n    return cast(TParam, value)\n"
  },
  {
    "path": "src/refind_btrfs/utility/injector_modules.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nfrom typing import Iterator\n\nfrom injector import Binder, Module, SingletonScope, multiprovider\nfrom transitions.core import State\nfrom watchdog.events import FileSystemEventHandler\n\nfrom refind_btrfs.boot.file_refind_config_provider import FileRefindConfigProvider\nfrom refind_btrfs.common import CheckableObserver\nfrom refind_btrfs.common.abc import BaseRunner\nfrom refind_btrfs.common.abc.factories import (\n    BaseDeviceCommandFactory,\n    BaseIconCommandFactory,\n    BaseLoggerFactory,\n    BaseSubvolumeCommandFactory,\n)\nfrom refind_btrfs.common.abc.providers import (\n    BasePackageConfigProvider,\n    BasePersistenceProvider,\n    BaseRefindConfigProvider,\n)\nfrom refind_btrfs.common.enums import StateNames\nfrom refind_btrfs.console import CLIRunner\nfrom refind_btrfs.service import SnapshotEventHandler, SnapshotObserver, WatchdogRunner\nfrom refind_btrfs.state_management import Model, States\nfrom refind_btrfs.system import (\n    BtrfsUtilSubvolumeCommandFactory,\n    PillowIconCommandFactory,\n    SystemDeviceCommandFactory,\n)\nfrom refind_btrfs.utility.helpers import has_method\n\nfrom .file_package_config_provider import FilePackageConfigProvider\nfrom .logger_factories import StreamLoggerFactory, SystemdLoggerFactory\nfrom .shelve_persistence_provider import ShelvePersistenceProvider\n\n\nclass CommonModule(Module):\n    def configure(self, binder: Binder) -> None:\n        binder.bind(BaseDeviceCommandFactory, to=SystemDeviceCommandFactory)\n        binder.bind(BaseSubvolumeCommandFactory, to=BtrfsUtilSubvolumeCommandFactory)\n        binder.bind(BaseIconCommandFactory, to=PillowIconCommandFactory)\n\n        # singletons\n        binder.bind(\n            BasePackageConfigProvider,\n            to=FilePackageConfigProvider,\n            scope=SingletonScope,\n        )\n        binder.bind(\n            BaseRefindConfigProvider, to=FileRefindConfigProvider, scope=SingletonScope\n        )\n        binder.bind(\n            BasePersistenceProvider, to=ShelvePersistenceProvider, scope=SingletonScope\n        )\n\n    @multiprovider\n    def provide_states(self, model: Model) -> States:\n        return list(self._get_all_states_for(model))\n\n    def _get_all_states_for(self, model: Model) -> Iterator[State]:\n        for state_name in StateNames:\n            value: str = state_name.value\n            arguments = [value]\n\n            if has_method(model, value):\n                arguments *= 2\n\n            yield State(*arguments)\n\n\nclass WatchdogModule(CommonModule):\n    def configure(self, binder: Binder) -> None:\n        super().configure(binder)\n\n        binder.bind(BaseRunner, to=WatchdogRunner)\n        binder.bind(CheckableObserver, to=SnapshotObserver)\n        binder.bind(FileSystemEventHandler, to=SnapshotEventHandler)\n        binder.bind(BaseLoggerFactory, to=SystemdLoggerFactory)\n\n\nclass CLIModule(CommonModule):\n    def configure(self, binder: Binder) -> None:\n        super().configure(binder)\n\n        binder.bind(BaseRunner, to=CLIRunner)\n        binder.bind(BaseLoggerFactory, to=StreamLoggerFactory)\n"
  },
  {
    "path": "src/refind_btrfs/utility/level_aware_formatter.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport logging\nfrom logging import Formatter, LogRecord\n\nfrom refind_btrfs.common import constants\n\n\nclass LevelAwareFormatter(Formatter):\n    def format(self, record: LogRecord) -> str:\n        levelno = record.levelno\n        fmt = constants.EMPTY_STR\n\n        if levelno == logging.INFO:\n            fmt = \"%(message)s\"\n        elif levelno == logging.WARNING:\n            fmt = \"%(levelname)s: %(message)s\"\n        else:\n            fmt = \"%(levelname)s (%(name)s/%(filename)s/%(funcName)s): %(message)s\"\n\n        formatter = Formatter(fmt)\n\n        return formatter.format(record)\n"
  },
  {
    "path": "src/refind_btrfs/utility/logger_factories.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport sys\nfrom logging import Handler, NullHandler, StreamHandler\n\nfrom systemd.journal import JournalHandler\n\nfrom refind_btrfs.common.abc.factories import BaseLoggerFactory\n\n\nclass NullLoggerFactory(BaseLoggerFactory):\n    def get_handler(self) -> Handler:\n        return NullHandler()\n\n\nclass StreamLoggerFactory(BaseLoggerFactory):\n    def get_handler(self) -> Handler:\n        return StreamHandler(sys.stdout)\n\n\nclass SystemdLoggerFactory(BaseLoggerFactory):\n    def get_handler(self) -> Handler:\n        return JournalHandler()\n"
  },
  {
    "path": "src/refind_btrfs/utility/shelve_persistence_provider.py",
    "content": "# region Licensing\n# SPDX-FileCopyrightText: 2020-2024 Luka Žaja <luka.zaja@protonmail.com>\n#\n# SPDX-License-Identifier: GPL-3.0-or-later\n\n\"\"\" refind-btrfs - Generate rEFInd manual boot stanzas from Btrfs snapshots\nCopyright (C) 2020-2024 Luka Žaja\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n# endregion\n\nimport shelve\nfrom pathlib import Path\nfrom shelve import Shelf\nfrom typing import Any, Optional, TypeVar, cast\n\nfrom semantic_version import Version\n\nfrom refind_btrfs.boot import RefindConfig\nfrom refind_btrfs.common import PackageConfig, constants\nfrom refind_btrfs.common.abc.providers import BasePersistenceProvider\nfrom refind_btrfs.common.enums import LocalDbKey\nfrom refind_btrfs.state_management.model import ProcessingResult\nfrom refind_btrfs.utility.helpers import checked_cast\n\nTItem = TypeVar(\"TItem\")\n\n\nclass ShelvePersistenceProvider(BasePersistenceProvider):\n    def __init__(self) -> None:\n        version_suffix = constants.DB_ITEM_VERSION_SUFFIX\n\n        self._db_filename = str(constants.DB_FILE)\n        self._current_versions = {\n            f\"{LocalDbKey.PACKAGE_CONFIG.value}_{version_suffix}\": Version(\"1.3.0\"),\n            f\"{LocalDbKey.REFIND_CONFIGS.value}_{version_suffix}\": Version(\"1.0.0\"),\n            f\"{LocalDbKey.PROCESSING_RESULT.value}_{version_suffix}\": Version(\"1.1.0\"),\n        }\n\n    def get_package_config(self) -> Optional[PackageConfig]:\n        db_key = LocalDbKey.PACKAGE_CONFIG.value\n\n        with shelve.open(self._db_filename) as local_db:\n            item = self._get_item(db_key, local_db)\n\n            if item is not None:\n                package_config = checked_cast(PackageConfig, item)\n\n                if not package_config.is_modified(constants.PACKAGE_CONFIG_FILE):\n                    return package_config\n\n        return None\n\n    def save_package_config(self, value: PackageConfig) -> None:\n        db_key = LocalDbKey.PACKAGE_CONFIG.value\n\n        with shelve.open(self._db_filename) as local_db:\n            self._save_item(value, db_key, local_db)\n\n    def get_refind_config(self, file_path: Path) -> Optional[RefindConfig]:\n        db_key = LocalDbKey.REFIND_CONFIGS.value\n\n        with shelve.open(self._db_filename) as local_db:\n            item = self._get_item(db_key, local_db)\n\n            if item is not None:\n                all_refind_configs = checked_cast(dict[Path, RefindConfig], item)\n                refind_config = all_refind_configs.get(file_path)\n\n                if refind_config is not None:\n                    if refind_config.is_modified(file_path):\n                        del all_refind_configs[file_path]\n\n                        self._save_item(all_refind_configs, db_key, local_db)\n                    else:\n                        return refind_config\n\n        return None\n\n    def save_refind_config(self, value: RefindConfig) -> None:\n        db_key = LocalDbKey.REFIND_CONFIGS.value\n\n        with shelve.open(self._db_filename) as local_db:\n            item = self._get_item(db_key, local_db)\n            all_refind_configs: Optional[dict[Path, RefindConfig]] = None\n\n            if item is not None:\n                all_refind_configs = checked_cast(dict[Path, RefindConfig], item)\n            else:\n                all_refind_configs = {}\n\n            file_path = value.file_path\n            all_refind_configs[file_path] = value\n\n            self._save_item(all_refind_configs, db_key, local_db)\n\n    def get_previous_run_result(self) -> ProcessingResult:\n        db_key = LocalDbKey.PROCESSING_RESULT.value\n\n        with shelve.open(self._db_filename) as local_db:\n            item = self._get_item(db_key, local_db)\n\n            if item is not None:\n                return cast(ProcessingResult, item)\n\n        return ProcessingResult.none()\n\n    def save_current_run_result(self, value: ProcessingResult) -> None:\n        db_key = LocalDbKey.PROCESSING_RESULT.value\n\n        with shelve.open(self._db_filename) as local_db:\n            self._save_item(value, db_key, local_db)\n\n    def _get_item(self, value_key: str, local_db: Shelf) -> Optional[Any]:\n        version_key = f\"{value_key}_{constants.DB_ITEM_VERSION_SUFFIX}\"\n        default_version = Version(\"0.0.0\")\n        current_version = self._current_versions[version_key]\n        actual_version = (\n            checked_cast(Version, local_db[version_key])\n            if version_key in local_db\n            else default_version\n        )\n\n        return local_db.get(value_key) if actual_version >= current_version else None\n\n    def _save_item(self, item: TItem, value_key: str, local_db: Shelf) -> None:\n        version_key = f\"{value_key}_{constants.DB_ITEM_VERSION_SUFFIX}\"\n        current_version = self._current_versions[version_key]\n\n        local_db[value_key] = item\n        local_db[version_key] = current_version\n"
  },
  {
    "path": "tests/.keep",
    "content": ""
  }
]