Debian Codegraph @

goodvibes/utils.py

raw
1 """Utility classes and functions for GoodVibes."""
2 import logging
3 import os.path
4 import sys
5 from datetime import datetime, timedelta
6 from typing import Optional
7
8 try:
9 from rich.console import Console
10 except ImportError:
11 Console = None
12
13
14 _console_stdout: Optional["Console"] = None
15 _console_dat: Optional["Console"] = None
16
17
18 def all_same(items):
19 """
20 Determine whether every element of `items` equals the first element.
21
22 Parameters:
23 items (Sequence): A non-empty sequence of comparable elements.
24
25 Returns:
26 True if every element equals the first element, False otherwise.
27
28 Raises:
29 IndexError: If `items` is empty.
30 """
31 return all(x == items[0] for x in items)
32
33
34 def setup_logging(filein, append):
35 """
36 Configure the 'goodvibes' logger to write to both stdout and a .dat file and initialize module-level Rich consoles.
37
38 Initializes the logger named 'goodvibes' to emit messages to standard output and to a file at "{filein}_{append}.dat". Opens the .dat file for writing and, if Rich is available, assigns module-level Console instances for stdout and the .dat file for later use.
39
40 Parameters:
41 filein (str): Prefix for the output file (e.g., "GoodVibes").
42 append (str): Suffix for the output file (e.g., "output").
43 """
44 global _console_stdout, _console_dat
45
46 logger = logging.getLogger('goodvibes')
47 logger.setLevel(logging.DEBUG)
48
49 formatter = logging.Formatter('%(message)s')
50
51 # stdout handler + terminal console
52 console_handler = logging.StreamHandler(sys.stdout)
53 console_handler.setFormatter(formatter)
54 console_handler.terminator = ''
55 logger.addHandler(console_handler)
56
57 if Console is not None:
58 _console_stdout = Console(highlight=False, force_terminal=True, width=200)
59
60 # .dat file: shared handle for both logging and Rich output
61 dat_path = f'{filein}_{append}.dat'
62 dat_fp = open(dat_path, 'w')
63
64 # Use StreamHandler with the open file, not FileHandler (avoids double-open)
65 datfile_handler = logging.StreamHandler(dat_fp)
66 datfile_handler.setFormatter(formatter)
67 datfile_handler.terminator = ''
68 logger.addHandler(datfile_handler)
69
70 if Console is not None:
71 _console_dat = Console(
72 file=dat_fp,
73 force_terminal=True, # emit box-drawing chars even though file is not a TTY
74 no_color=True, # strip ANSI color codes
75 highlight=False, # don't auto-highlight tokens
76 )
77
78
79 def fatal(message):
80 """
81 Log a critical error message and terminate the process.
82
83 Shuts down the logging subsystem and exits the process with status code 1.
84
85 Parameters:
86 message (str): The message to emit at the critical level.
87 """
88 log = logging.getLogger('goodvibes')
89 log.critical(message + "\n")
90 logging.shutdown()
91 sys.exit(1)
92
93
94 def add_time(tm, cpu):
95 """
96 Create a datetime representing tm's day/time advanced by an elapsed CPU-style interval.
97
98 Parameters:
99 tm (datetime): Source datetime whose day, hour, minute, second, and microsecond are used.
100 cpu (Sequence[int]): Elapsed time as [days, hrs, mins, secs, msecs].
101
102 Returns:
103 datetime: A new datetime with year set to 100 and month set to 1, using tm's day/time
104 plus the interval from `cpu` (milliseconds interpreted as 1/1000 second).
105 """
106 [days, hrs, mins, secs, msecs] = cpu
107 fulldate = datetime(100, 1, tm.day, tm.hour, tm.minute, tm.second, tm.microsecond)
108 fulldate = fulldate + timedelta(days=days, hours=hrs, minutes=mins, seconds=secs, microseconds=msecs * 1000)
109 return fulldate
110
111
112 def display_name(file):
113 """
114 Get the basename of a file path without its extension for display.
115
116 Parameters:
117 file (str): Path or filename from which to extract the display name.
118
119 Returns:
120 display_name (str): The filename portion of `file` with the final extension removed.
121 """
122 return os.path.splitext(os.path.basename(file))[0]
123
124
125 def natural_key(path):
126 """Sort key that orders ``conf_2`` before ``conf_10`` (and before ``conf_a``).
127
128 Splits on digit runs and treats them as integers so ordinary string
129 comparison won't put ``conf_10`` between ``conf_1`` and ``conf_2``.
130 Comparison uses the basename so files from different directories with the
131 same name don't separate solely by directory path.
132 """
133 import re
134 base = os.path.basename(path)
135 return [int(t) if t.isdigit() else t.lower()
136 for t in re.split(r'(\d+)', base)]
137
138
139 def get_console_stdout() -> "Console":
140 """
141 Get the Rich Console configured for colored stdout output.
142
143 Returns:
144 Console: The Rich Console instance used for stdout.
145
146 Raises:
147 RuntimeError: If `setup_logging()` has not been called and the console is not initialized.
148 """
149 if _console_stdout is None:
150 raise RuntimeError("setup_logging() must be called before get_console_stdout()")
151 return _console_stdout
152
153
154 def get_console_dat() -> "Console":
155 """Return the Rich Console for the .dat file (no color, box-drawing chars)."""
156 if _console_dat is None:
157 raise RuntimeError("setup_logging() must be called before get_console_dat()")
158 return _console_dat