Skip to content

Commit

Permalink
use annotations instead of typing
Browse files Browse the repository at this point in the history
  • Loading branch information
abhijeetSaroha committed Sep 30, 2024
1 parent 4fc22fe commit 098c057
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 31 deletions.
24 changes: 12 additions & 12 deletions src/makim/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import os
import sys

from typing import Any, Callable, Dict, List, Optional, Type, Union, cast
from typing import Any, Callable, Optional, Type, Union, cast

import click
import typer
Expand Down Expand Up @@ -77,7 +77,7 @@ def main(
raise typer.Exit(0)


def suggest_command(user_input: str, available_commands: List[str]) -> str:
def suggest_command(user_input: str, available_commands: list[str]) -> str:
"""
Suggest the closest command to the user input using fuzzy search.
Expand Down Expand Up @@ -173,7 +173,7 @@ def get_default_value_str(arg_type: str, value: Any) -> str:
return f'{value or 0}'


def create_args_string(args: Dict[str, str]) -> str:
def create_args_string(args: dict[str, str]) -> str:
"""Return a string for arguments for a function for typer."""
args_rendered = []

Expand All @@ -185,7 +185,7 @@ def create_args_string(args: Dict[str, str]) -> str:
')'
)

args_data = cast(Dict[str, Dict[str, str]], args.get('args', {}))
args_data = cast(dict[str, dict[str, str]], args.get('args', {}))
for name, spec in args_data.items():
name_clean = name.replace('-', '_')
arg_type = normalize_string_type(spec.get('type', 'str'))
Expand Down Expand Up @@ -214,7 +214,7 @@ def create_args_string(args: Dict[str, str]) -> str:


def apply_click_options(
command_function: Callable[..., Any], options: Dict[str, Any]
command_function: Callable[..., Any], options: dict[str, Any]
) -> Callable[..., Any]:
"""
Apply Click options to a Typer command function.
Expand All @@ -236,7 +236,7 @@ def apply_click_options(
str, Optional[Union[str, int, float, bool, Type[Any]]]
] = {}

opt_data = cast(Dict[str, str], opt_details)
opt_data = cast(dict[str, str], opt_details)
opt_type_str = normalize_string_type(opt_data.get('type', 'str'))
opt_default = get_default_value(opt_type_str, opt_data.get('default'))

Expand All @@ -263,7 +263,7 @@ def apply_click_options(
return command_function


def create_dynamic_command(name: str, args: Dict[str, str]) -> None:
def create_dynamic_command(name: str, args: dict[str, str]) -> None:
"""
Dynamically create a Typer command with the specified options.
Expand All @@ -277,7 +277,7 @@ def create_dynamic_command(name: str, args: Dict[str, str]) -> None:
args_str = create_args_string(args)
args_param_list = [f'"task": "{name}"']

args_data = cast(Dict[str, Dict[str, str]], args.get('args', {}))
args_data = cast(dict[str, dict[str, str]], args.get('args', {}))

for arg, arg_details in args_data.items():
arg_clean = arg.replace('-', '_')
Expand All @@ -303,19 +303,19 @@ def create_dynamic_command(name: str, args: Dict[str, str]) -> None:

function_code += f' makim.run({args_param_str})\n'

local_vars: Dict[str, Any] = {}
local_vars: dict[str, Any] = {}
exec(function_code, globals(), local_vars)
dynamic_command = decorator(local_vars['dynamic_command'])

# Apply Click options to the Typer command
if 'args' in args:
options_data = cast(Dict[str, Dict[str, Any]], args.get('args', {}))
options_data = cast(dict[str, dict[str, Any]], args.get('args', {}))
dynamic_command = apply_click_options(dynamic_command, options_data)


def extract_root_config(
cli_list: list[str] = sys.argv,
) -> Dict[str, str | bool]:
) -> dict[str, str | bool]:
"""Extract the root configuration from the CLI."""
params = cli_list[1:]

Expand Down Expand Up @@ -407,7 +407,7 @@ def run_app() -> None:

# create tasks data
# group_names = list(makim.global_data.get('groups', {}).keys())
tasks: Dict[str, Any] = {}
tasks: dict[str, Any] = {}
for group_name, group_data in makim.global_data.get('groups', {}).items():
for task_name, task_data in group_data.get('tasks', {}).items():
tasks[f'{group_name}.{task_name}'] = task_data
Expand Down
38 changes: 19 additions & 19 deletions src/makim/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

from copy import deepcopy
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union, cast
from typing import Any, Dict, List, Optional, Union, cast

import dotenv
import sh
Expand Down Expand Up @@ -95,23 +95,23 @@ class Makim:
file: str = '.makim.yaml'
dry_run: bool = False
verbose: bool = False
global_data: Dict[str, Any] = {}
global_data: dict[str, Any] = {}
shell_app: sh.Command = sh.xonsh
shell_args: list[str] = []
tmp_suffix: str = '.makim'

# temporary variables
env: Dict[str, Any] = {} # initial env
env_scoped: Dict[str, Any] = {} # current env
env: dict[str, Any] = {} # initial env
env_scoped: dict[str, Any] = {} # current env
# initial working directory
working_directory: Optional[Path] = None
# current working directory
working_directory_scoped: Optional[Path] = None
args: Optional[Dict[str, Any]] = None
args: Optional[dict[str, Any]] = None
group_name: str = 'default'
group_data: Dict[str, Any] = {}
group_data: dict[str, Any] = {}
task_name: str = ''
task_data: Dict[str, Any] = {}
task_data: dict[str, Any] = {}

def __init__(self) -> None:
"""Prepare the Makim class with the default configuration."""
Expand Down Expand Up @@ -272,7 +272,7 @@ def update_working_directory(
return working_dir

def _extract_shell_app_config(
self, scoped_config: Dict[str, Any]
self, scoped_config: dict[str, Any]
) -> AppConfigType:
"""Extract the shell app configuration from the scoped config data."""
shell_app_data: AppConfigType = scoped_config.get('backend', {})
Expand Down Expand Up @@ -327,7 +327,7 @@ def _load_shell_app(self) -> None:
shell_config = tmp_config

cmd_name = str(shell_config.get('app', ''))
cmd_args: list[str] = cast(List[str], shell_config.get('args', []))
cmd_args: list[str] = cast(list[str], shell_config.get('args', []))
cmd_tmp_suffix: str = str(
shell_config.get('suffix', tmp_suffix_default)
)
Expand All @@ -342,7 +342,7 @@ def _load_shell_app(self) -> None:
self.shell_args = cmd_args
self.tmp_suffix = cmd_tmp_suffix

def _load_dotenv(self, data_scope: Dict[str, Any]) -> Dict[str, str]:
def _load_dotenv(self, data_scope: dict[str, Any]) -> dict[str, str]:
env_file = data_scope.get('env-file')
if not env_file:
return {}
Expand All @@ -363,16 +363,16 @@ def _load_dotenv(self, data_scope: Dict[str, Any]) -> Dict[str, str]:

def _load_scoped_data(
self, scope: str
) -> Tuple[Dict[str, str], Dict[str, str]]:
) -> tuple[dict[str, str], dict[str, str]]:
scope_options = ('global', 'group', 'task')
if scope not in scope_options:
raise Exception(f'The given scope `{scope}` is not valid.')

def _render_env_inplace(
env_user: Dict[str, Any],
env_file: Dict[str, Any],
variables: Dict[str, Any],
env: Dict[str, Any],
env_user: dict[str, Any],
env_file: dict[str, Any],
variables: dict[str, Any],
env: dict[str, Any],
) -> None:
env.update(env_file)
for k, v in env_user.items():
Expand All @@ -383,7 +383,7 @@ def _render_env_inplace(
scope_id = scope_options.index(scope)

env = deepcopy(dict(os.environ))
variables: Dict[str, Any] = {}
variables: dict[str, Any] = {}

if scope_id >= SCOPE_GLOBAL:
env_user = self.global_data.get('env', {})
Expand Down Expand Up @@ -452,7 +452,7 @@ def _load_task_args(self) -> None:
)

# run commands
def _run_hooks(self, args: Dict[str, Any], hook_type: str) -> None:
def _run_hooks(self, args: dict[str, Any], hook_type: str) -> None:
if not self.task_data.get('hooks', {}).get(hook_type):
return
makim_hook = deepcopy(self)
Expand Down Expand Up @@ -516,7 +516,7 @@ def _run_hooks(self, args: Dict[str, Any], hook_type: str) -> None:

makim_hook.run(deepcopy(args_hook))

def _run_command(self, args: Dict[str, Any]) -> None:
def _run_command(self, args: dict[str, Any]) -> None:
cmd = self.task_data.get('run', '').strip()
if 'vars' not in self.group_data:
self.group_data['vars'] = {}
Expand Down Expand Up @@ -607,7 +607,7 @@ def load(
self._verify_config()
self.env = self._load_dotenv(self.global_data)

def run(self, args: Dict[str, Any]) -> None:
def run(self, args: dict[str, Any]) -> None:
"""Run makim task code."""
self.args = args

Expand Down

0 comments on commit 098c057

Please sign in to comment.