Coverage for src/system/platform.py: 83.72%
43 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-08 13:49 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-08 13:49 +0000
1#!/usr/bin/env python3
3# Standard libraries
4from os import access, environ, R_OK, sep
5from os.path import expanduser
6from pathlib import Path
7from sys import platform, stdin, stdout
8from typing import Optional
10# Platform
11class Platform:
13 # Environment
14 ENV_SIMULATE_MAC_OS: str = 'SIMULATE_MAC_OS'
15 ENV_SUDO_USER: str = 'SUDO_USER'
17 # Constants
18 IS_LINUX: bool = platform in ['linux', 'linux2']
19 IS_MAC_OS: bool = platform in ['darwin'] or ENV_SIMULATE_MAC_OS in environ
20 IS_SIMULATED: bool = ENV_SIMULATE_MAC_OS in environ
21 IS_WINDOWS: bool = platform in ['win32', 'win64']
23 # Separators
24 PATH_SEPARATOR: str = sep
26 # TTYs
27 IS_TTY_STDIN: bool = stdin.isatty() and stdin.encoding != 'cp1252'
28 IS_TTY_STDOUT: bool = stdout.isatty()
29 IS_TTY_UTF8: bool = str(stdout.encoding).lower() == 'utf-8'
31 # Outputs
32 IS_FLUSH_ENABLED: bool = IS_TTY_STDOUT or IS_WINDOWS
34 # Users
35 IS_USER_SUDO: bool = ENV_SUDO_USER in environ
36 USER_SUDO: str = environ[ENV_SUDO_USER] if IS_USER_SUDO else ''
38 # Bashrc
39 @staticmethod
40 def bashrc() -> Optional[Path]:
42 # Variables
43 bashrc: None | Path = None
44 home: Path = Path.home()
46 # Detect .bashrc
47 if Path(home / '.bashrc').exists():
48 bashrc = Path(home / '.bashrc')
50 # Detect .bash_user.rc
51 if Path(home / '.bash_user.rc').exists():
52 bashrc = home / '.bash_user.rc'
54 # Result
55 return bashrc
57 # Flush
58 @staticmethod
59 def flush() -> None:
61 # Flush output
62 print(
63 '',
64 end='',
65 flush=Platform.IS_FLUSH_ENABLED,
66 )
68 # Userspace
69 @staticmethod
70 def userspace(name: str) -> Path:
72 # Variables
73 home: None | Path = None
75 # Elevated home
76 if Platform.IS_USER_SUDO: # pragma: linux cover
77 home = Path(expanduser(f'~{Platform.USER_SUDO}'))
78 if not access(home, R_OK): # pragma: no cover
79 home = None
81 # Default home
82 if not home or not home.is_dir():
83 home = Path.home()
85 # Windows userspace
86 if Platform.IS_WINDOWS: # pragma: windows cover
87 return home / 'AppData' / 'Local' / name
89 # macOS userspace
90 if Platform.IS_MAC_OS: # pragma: macos cover
91 return home / 'Library' / 'Preferences' / name
93 # Linux userspace
94 return home / '.config' / name # pragma: linux cover