Coverage for src/features/mise.py: 56.63%
83 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-07 23:52 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-07 23:52 +0000
1#!/usr/bin/env python3
3# Standard libraries
4from json import loads
5from os import environ
6from pathlib import Path
7from re import MULTILINE, search, sub
8from typing import Any, Dict, List, Optional, Tuple
10# Components
11from ..package.version import Version
12from ..system.commands import Commands
14# Mise class
15class Mise:
17 # Constants
18 BACKEND_DEFAULT: str = 'pipx'
19 BACKENDS_PYTHON: List[str] = ['pipx', 'pypi']
20 BINARY: str = 'mise'
21 CONFIG_FILE: str = 'config.toml'
22 ENV_CONFIG_DIR: str = 'MISE_CONFIG_DIR'
23 ENV_DATA_DIR: str = 'MISE_DATA_DIR'
24 ENV_GLOBAL_CONFIG_FILE: str = 'MISE_GLOBAL_CONFIG_FILE'
25 ENV_XDG_CONFIG_HOME: str = 'XDG_CONFIG_HOME'
26 INSTALLS: str = 'installs'
27 VERSION_LATEST: str = 'latest'
29 # Arguments
30 @staticmethod
31 def arguments(config: str, specification: str = '') -> List[str]:
33 # Use default configuration
34 if config and specification \
35 and Path(config).expanduser().resolve() == Mise.target(specification):
36 return []
38 # Use global configuration
39 if config and Path(config).expanduser().resolve() == Mise.config_global():
40 return [
41 '--global',
42 ]
44 # Use configuration file
45 if config:
46 return [
47 '--path',
48 config,
49 ]
51 # Use local configuration
52 return []
54 # Dependencies
55 @staticmethod
56 def dependencies(
57 binary: str,
58 package: str,
59 version: str = VERSION_LATEST,
60 ) -> Optional[bool]:
62 # Variables
63 config: str
64 provided: str
65 tool: Optional[Tuple[str, str]]
67 # Ignore missing mise
68 if not Mise.exists():
69 return None
71 # Detect packages
72 provided = Commands.output(Mise.BINARY, [
73 'which',
74 binary,
75 ], quiet=True)
76 tool = Mise.tool(provided) if provided else None # pragma: no cover
78 # Upgrade packages
79 if provided and version == Mise.VERSION_LATEST: # pragma: no cover
80 return Commands.mise([
81 'upgrade',
82 tool[0] if tool else package,
83 ])
85 # Detect configuration file
86 if Mise.managed(): # pragma: no cover
87 config = Mise.config()
88 elif provided: # pragma: no cover
89 config = tool[1] if tool else ''
90 else: # pragma: no cover
91 return None
93 # Install packages in the configuration file
94 specification: str = f'{package}@{version}' # pragma: no cover
95 return Commands.mise( # pragma: no cover
96 ['use'] + Mise.arguments(config, specification) + [specification])
98 # Configuration
99 @staticmethod
100 def config() -> str:
102 # Detect configuration file
103 tool: Optional[Tuple[str, str]] = Mise.tool(Version.path())
104 if tool: # pragma: no cover
105 return tool[1]
107 # Fallback
108 return ''
110 # Configuration global
111 @staticmethod
112 def config_global() -> Path:
114 # Detect custom global configuration file
115 config_file: str = environ.get(Mise.ENV_GLOBAL_CONFIG_FILE, '')
116 if config_file:
117 return Path(config_file).expanduser().resolve()
119 # Detect global configuration folder
120 config_dir: str = environ.get(Mise.ENV_CONFIG_DIR, '')
121 if not config_dir:
122 config_dir = str(
123 Path(environ.get(Mise.ENV_XDG_CONFIG_HOME, '~/.config')) / Mise.BINARY)
125 # Result
126 return (Path(config_dir) / Mise.CONFIG_FILE).expanduser().resolve()
128 # Exists
129 @staticmethod
130 def exists() -> bool:
132 # Check if binary exists
133 return Commands.exists(Mise.BINARY)
135 # Installation
136 @staticmethod
137 def installation() -> str:
139 # Variables
140 parts = Path(Version.path()).parts
142 # Detect custom mise installs
143 data_dir: str = environ.get(Mise.ENV_DATA_DIR, '')
144 if data_dir:
145 installs = Path(data_dir).expanduser().parts + (Mise.INSTALLS, )
146 if parts[0:len(installs)] == installs and len(parts) > len(installs):
147 return parts[len(installs)] # pragma: no cover
149 # Detect default mise installs
150 for index in range(len(parts) - 2):
151 if parts[index] == Mise.BINARY and parts[index + 1] == Mise.INSTALLS:
152 return parts[index + 2] # pragma: no cover
154 # Fallback
155 return ''
157 # Managed
158 @staticmethod
159 def managed() -> bool:
161 # Check if running from mise
162 return bool(Mise.installation())
164 # Target
165 @staticmethod
166 def target(specification: str) -> Optional[Path]:
168 # Detect default configuration file
169 output: str = Commands.output(Mise.BINARY, [
170 'use',
171 '--dry-run',
172 specification,
173 ], errors=True)
174 match = search(
175 r'^mise would \w+ (.+) \(',
176 sub(r'\x1b\[[0-9;]*m', '', output),
177 MULTILINE,
178 )
179 if match: # pragma: no cover
180 return Path(match.group(1)).expanduser().resolve()
182 # Fallback
183 return None
185 # Tool
186 @staticmethod
187 def tool(path: str) -> Optional[Tuple[str, str]]:
189 # Variables
190 resolved: Path = Path(path).resolve()
192 # Find mise tool
193 for name, entries in Mise.tools().items(): # pragma: no cover
194 for entry in entries:
195 install: str = entry.get('install_path', '')
196 if not install:
197 continue
198 install_path: Path = Path(install).resolve()
199 if resolved == install_path or install_path in resolved.parents:
200 return name, str(entry.get('source', {}).get('path', ''))
202 # Fallback
203 return None
205 # Tools
206 @staticmethod
207 def tools() -> Dict[str, List[Dict[str, Any]]]:
209 # Ignore missing mise
210 if not Mise.exists():
211 return {}
213 # Get current mise tools
214 try:
215 tools = loads(
216 Commands.output(Mise.BINARY, [
217 'ls',
218 '--current',
219 '--json',
220 ], quiet=True))
221 if isinstance(tools, dict): # pragma: no cover
222 return tools
223 except ValueError: # pragma: no cover
224 pass
226 # Fallback
227 return {} # pragma: no cover
229 # Package
230 @staticmethod
231 def package(name: str) -> str:
233 # Detect mise tool
234 tool: Optional[Tuple[str, str]] = Mise.tool(Version.path())
235 if tool: # pragma: no cover
236 return tool[0]
238 # Detect mise backend
239 backend: str = Mise.installation().split('-', maxsplit=1)[0]
240 if backend not in Mise.BACKENDS_PYTHON:
241 backend = Mise.BACKEND_DEFAULT
243 # Result
244 return f'{backend}:{name}'