Skip to content

Commit

Permalink
qtile migrate - defer libcst import
Browse files Browse the repository at this point in the history
libcst import can be slow so we only import it when we're actually
executing a `qtile migrate` command.
  • Loading branch information
elParaguayo committed Nov 10, 2024
1 parent b31f0d3 commit 9bf4f33
Showing 1 changed file with 18 additions and 11 deletions.
29 changes: 18 additions & 11 deletions libqtile/scripts/migrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,9 @@
if TYPE_CHECKING:
from collections.abc import Iterator

BACKUP_SUFFIX = ".migrate.bak"


try:
import libcst
except ImportError:
pass

BACKUP_SUFFIX = ".migrate.bak"


class AbortMigration(Exception):
Expand All @@ -50,6 +46,21 @@ class SkipFile(Exception):
pass


def needs_libcst(func):
def _wrapper(*args, **kwargs):
if "libcst" not in sys.modules:
try:
global libcst
libcst = __import__("libcst", globals(), locals())
except ImportError:
print("libcst is needed for 'qtile migrate' commands.")
print("Please install it and try again.")
sys.exit(1)
func(*args, **kwargs)

return _wrapper


def version_tuple(value: str) -> tuple[int, ...]:
try:
val = tuple(int(x) for x in value.split("."))
Expand All @@ -72,16 +83,12 @@ class QtileMigrate:
without needing to pass them around all the time.
"""

@needs_libcst
def __call__(self, args: argparse.Namespace) -> None:
"""
This is called by ArgParse when we run `qtile migrate`. The parsed options are
passed as an argument.
"""
if "libcst" not in sys.modules:
print("libcst can't be found. Unable to migrate config file.")
print("Please install it and try again.")
sys.exit(1)

self.args = args
self.filter_migrations()

Expand Down

0 comments on commit 9bf4f33

Please sign in to comment.