mmit-clitheme 0.15.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cli_theme/__init__.py +47 -0
- cli_theme/arguments.py +265 -0
- cli_theme/bash/cli.lib.sh +475 -0
- cli_theme/bash/make.lib.sh +138 -0
- cli_theme/cli.py +276 -0
- cli_theme/deno/deno.json +10 -0
- cli_theme/deno/help.ts +150 -0
- cli_theme/deno/mod.ts +413 -0
- cli_theme/export.py +221 -0
- cli_theme/i18n.py +18 -0
- cli_theme/locales/de/LC_MESSAGES/cli_theme.mo +0 -0
- cli_theme/locales/de/LC_MESSAGES/cli_theme.po +328 -0
- cli_theme/output.py +261 -0
- cli_theme/skill.py +107 -0
- cli_theme/templates/classic.theme +46 -0
- cli_theme/templates/earth.theme +46 -0
- cli_theme/templates/forest.theme +46 -0
- cli_theme/templates/mono.theme +46 -0
- cli_theme/templates/neon.theme +46 -0
- cli_theme/templates/night.theme +46 -0
- cli_theme/templates/ocean.theme +46 -0
- cli_theme/templates/shell.theme +46 -0
- cli_theme/templates/sunset.theme +46 -0
- cli_theme/theme.py +422 -0
- mmit_clitheme-0.15.0.data/scripts/clilib-path +74 -0
- mmit_clitheme-0.15.0.dist-info/METADATA +482 -0
- mmit_clitheme-0.15.0.dist-info/RECORD +33 -0
- mmit_clitheme-0.15.0.dist-info/WHEEL +5 -0
- mmit_clitheme-0.15.0.dist-info/entry_points.txt +3 -0
- mmit_clitheme-0.15.0.dist-info/licenses/LICENSE +287 -0
- mmit_clitheme-0.15.0.dist-info/licenses/LICENSE.de.txt +101 -0
- mmit_clitheme-0.15.0.dist-info/licenses/LICENSING.md +97 -0
- mmit_clitheme-0.15.0.dist-info/top_level.txt +1 -0
cli_theme/deno/mod.ts
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ausgabe im CLI-Theme von clitheme für Deno.
|
|
3
|
+
*
|
|
4
|
+
* Farben und Abstände kommen aus `clitheme export --json` (CLI_THEME wählt das
|
|
5
|
+
* Theme). Überschrift, Zeile, Bezeichnung · Wert, Statuszeile und Hinweis sehen
|
|
6
|
+
* aus wie die gleichnamigen Helfer in BashLib cli.lib.sh (printThemeHeading,
|
|
7
|
+
* printThemeRow, printThemeValue, printThemeStatus, printThemeHint), die auch
|
|
8
|
+
* make.lib.sh für Makefiles nutzt. Dazu Prüfzeile und Handlungshinweis für
|
|
9
|
+
* Prüfwerkzeuge wie docs-check; sie brechen Wörter um, damit keine Zeile breiter
|
|
10
|
+
* wird als THEME_WIDTH_HELP. Farben nur am Terminal, ohne NO_COLOR und ohne
|
|
11
|
+
* TERM=dumb; sonst die Zeilen ohne Escape-Folgen, mit denselben Abständen.
|
|
12
|
+
*
|
|
13
|
+
* Dazu die --help-Ausgabe wie bei changelog (help, siehe help.ts).
|
|
14
|
+
*
|
|
15
|
+
* Das Package hängt nur von Deno und clitheme ab und kommt mit clitheme; den Pfad
|
|
16
|
+
* dieser Datei in der installierten Version nennt `clitheme export --deno`.
|
|
17
|
+
* Übernommen aus ProjectTools src/deno/clitheme. Berechtigungen:
|
|
18
|
+
* --allow-run=clitheme, für TERM=dumb zusätzlich --allow-env=TERM (ohne gilt TERM
|
|
19
|
+
* als nicht dumb).
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { formatHelp, type HelpSpec } from "./help.ts";
|
|
23
|
+
|
|
24
|
+
export { formatHelp, type HelpItem, type HelpSection, type HelpSpec, wrapText } from "./help.ts";
|
|
25
|
+
|
|
26
|
+
/** Farbrollen von clitheme, als THEME_COLOR_<ROLLE> im Export. */
|
|
27
|
+
export type Role =
|
|
28
|
+
| "GROUP"
|
|
29
|
+
| "TARGET"
|
|
30
|
+
| "DESC"
|
|
31
|
+
| "VALUE"
|
|
32
|
+
| "HINT"
|
|
33
|
+
| "ACCENT"
|
|
34
|
+
| "SUCCESS"
|
|
35
|
+
| "WARNING"
|
|
36
|
+
| "DANGER"
|
|
37
|
+
| "SERVER";
|
|
38
|
+
|
|
39
|
+
/** Kurzformen der Statusrollen wie bei printThemeStatus (OK, WARN, ERR). */
|
|
40
|
+
export type StatusRole = Role | "OK" | "WARN" | "ERR";
|
|
41
|
+
|
|
42
|
+
/** Werte aus `clitheme export --json`; Farben als Escape-Folgen, Abstände als Zahlen. */
|
|
43
|
+
export interface ThemeValues {
|
|
44
|
+
THEME_NAME: string;
|
|
45
|
+
THEME_NOTICE: string;
|
|
46
|
+
THEME_INDENT_GROUP: string;
|
|
47
|
+
THEME_INDENT_TARGET: string;
|
|
48
|
+
THEME_INDENT_HINT: string;
|
|
49
|
+
THEME_WIDTH_TARGET: number;
|
|
50
|
+
THEME_COLUMN_GAP: number;
|
|
51
|
+
THEME_WIDTH_HELP: number;
|
|
52
|
+
THEME_GROUP_SPACING: number;
|
|
53
|
+
[name: string]: string | number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface LoadOptions {
|
|
57
|
+
/** Befehl für den Export, Standard `clitheme export --json` (für Tests ersetzbar). */
|
|
58
|
+
command?: string[];
|
|
59
|
+
/** Farben erzwingen oder abschalten; ohne Angabe wie BashLib (Terminal, NO_COLOR, TERM). */
|
|
60
|
+
color?: boolean;
|
|
61
|
+
/** Lange Zeilen umbrechen; ohne Angabe nur am Terminal, damit Pipes jede Meldung am Stück sehen. */
|
|
62
|
+
wrap?: boolean;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const RESET = "\x1b[0m";
|
|
66
|
+
// deno-lint-ignore no-control-regex -- Escape-Folgen sind genau, was hier entfernt wird.
|
|
67
|
+
const ANSI = /\x1b\[[0-9;]*m/g;
|
|
68
|
+
// deno-lint-ignore no-control-regex -- Steuerzeichen sind genau, was hier ersetzt wird.
|
|
69
|
+
const CONTROL = /\x1b\[[0-9;]*m|[\x00-\x08\x0b-\x1f\x7f-\x9f]/g;
|
|
70
|
+
// deno-lint-ignore no-control-regex -- Farbwert aus dem Export: leer oder eine Farbfolge.
|
|
71
|
+
const COLOR = /^(\x1b\[[0-9;]+m)?$/;
|
|
72
|
+
/** Breiten und Abstände ohne brauchbaren Wert aus dem Export, wie die classic-Vorlage. */
|
|
73
|
+
const NUMBERS: Record<string, number> = {
|
|
74
|
+
THEME_WIDTH_TARGET: 21,
|
|
75
|
+
THEME_COLUMN_GAP: 2,
|
|
76
|
+
THEME_WIDTH_HELP: 120,
|
|
77
|
+
THEME_GROUP_SPACING: 1,
|
|
78
|
+
};
|
|
79
|
+
/** Einrückungen ohne brauchbaren Wert aus dem Export, wie die classic-Vorlage. */
|
|
80
|
+
const INDENTS: Record<string, string> = {
|
|
81
|
+
THEME_INDENT_GROUP: " ",
|
|
82
|
+
THEME_INDENT_TARGET: " ",
|
|
83
|
+
THEME_INDENT_HINT: " ",
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Entschärft Steuerzeichen in einem Text: Es bleiben Zeilenumbruch, Tabulator und Farbfolgen
|
|
88
|
+
* (ESC [ Ziffern ; m); jedes andere Steuerzeichen (übrige C0-Zeichen, DEL, die C1-Zeichen
|
|
89
|
+
* U+0080 bis U+009F) wird zu „�“. So bringt ein Wert von außen keine Steuerfolge ans
|
|
90
|
+
* Terminal, etwa Fenstertitel setzen oder Bildschirm löschen. Dieselbe Regel gilt in der
|
|
91
|
+
* Bash-Lib (themeGuard) und in der Python-Bibliothek (guard).
|
|
92
|
+
*/
|
|
93
|
+
export function guard(text: string): string {
|
|
94
|
+
return text.replace(CONTROL, (found) => found.length > 1 ? found : "\ufffd");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Werte aus dem Export, geprüft wie themeImport der Bash-Lib: Farben nur leer oder als
|
|
99
|
+
* Farbfolge, sonst ohne Farbe; Einrückungen nur aus Leerzeichen und Breiten nur als ganze
|
|
100
|
+
* Zahlen von 0 bis 999, sonst die Werte von classic; übrige Texte ohne Steuerzeichen.
|
|
101
|
+
*/
|
|
102
|
+
function checked(values: ThemeValues): ThemeValues {
|
|
103
|
+
const result: ThemeValues = { ...values };
|
|
104
|
+
for (const [name, value] of Object.entries(values)) {
|
|
105
|
+
if (name.startsWith("THEME_COLOR_")) {
|
|
106
|
+
result[name] = typeof value === "string" && COLOR.test(value) ? value : "";
|
|
107
|
+
} else if (name in INDENTS) {
|
|
108
|
+
result[name] = typeof value === "string" && /^ *$/.test(value) ? value : INDENTS[name];
|
|
109
|
+
} else if (name in NUMBERS) {
|
|
110
|
+
// Wie themeNumber der Bash-Lib: nur ganze Zahlen von 0 bis 999.
|
|
111
|
+
const usable = typeof value === "number" && Number.isInteger(value) && value >= 0 &&
|
|
112
|
+
value <= 999;
|
|
113
|
+
result[name] = usable ? value : NUMBERS[name];
|
|
114
|
+
} else if (typeof value === "string") {
|
|
115
|
+
result[name] = guard(value);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return result;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Teil einer Zeile; ohne Rolle ungefärbt. */
|
|
122
|
+
export interface Piece {
|
|
123
|
+
text: string;
|
|
124
|
+
role?: Role;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Wort in einer Zeile; `glue`: Teil des vorigen Worts, ohne Leerzeichen davor. */
|
|
128
|
+
interface Word extends Piece {
|
|
129
|
+
glue: boolean;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Teilt ein Wort in Stücke von höchstens `room` Zeichen, bevorzugt nach „/“ oder „,“
|
|
134
|
+
* (Pfade, Pfadlisten), sonst mitten im Wort.
|
|
135
|
+
*/
|
|
136
|
+
function splitWord(word: string, room: number): string[] {
|
|
137
|
+
const parts: string[] = [];
|
|
138
|
+
for (const segment of word.match(/[^/,]*[/,]|[^/,]+$/g) ?? [word]) {
|
|
139
|
+
const chars = [...segment];
|
|
140
|
+
for (let at = 0; at < chars.length; at += room) parts.push(chars.slice(at, at + room).join(""));
|
|
141
|
+
}
|
|
142
|
+
return parts;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Breite ohne Escape-Folgen, Umlaute und Pfeile als ein Zeichen. */
|
|
146
|
+
function visible(text: string): number {
|
|
147
|
+
return [...plain(text)].length;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Text ohne Farb-Escape-Folgen. */
|
|
151
|
+
export function plain(text: string): string {
|
|
152
|
+
return text.replace(ANSI, "");
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Farben wie themeStyle in BashLib: nur am Terminal, ohne NO_COLOR, ohne TERM=dumb. */
|
|
156
|
+
export function colorWanted(): boolean {
|
|
157
|
+
if (!Deno.stdout.isTerminal() || Deno.noColor) return false;
|
|
158
|
+
const term = Deno.permissions.querySync({ name: "env", variable: "TERM" }).state === "granted"
|
|
159
|
+
? Deno.env.get("TERM")
|
|
160
|
+
: undefined;
|
|
161
|
+
return term !== "dumb";
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Liest das Theme mit `clitheme export --json`; clitheme ist Voraussetzung. */
|
|
165
|
+
export function loadValues(command = ["clitheme", "export", "--json"]): ThemeValues {
|
|
166
|
+
let output: Deno.CommandOutput;
|
|
167
|
+
try {
|
|
168
|
+
output = new Deno.Command(command[0], { args: command.slice(1), stderr: "piped" })
|
|
169
|
+
.outputSync();
|
|
170
|
+
} catch (error) {
|
|
171
|
+
throw new Error(`clitheme fehlt oder ist nicht ausführbar: ${(error as Error).message}`);
|
|
172
|
+
}
|
|
173
|
+
if (!output.success) {
|
|
174
|
+
const reason = new TextDecoder().decode(output.stderr).trim();
|
|
175
|
+
throw new Error(`clitheme export --json scheiterte${reason ? `: ${reason}` : ""}`);
|
|
176
|
+
}
|
|
177
|
+
return JSON.parse(new TextDecoder().decode(output.stdout)) as ThemeValues;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Ausgabe im Theme; jede Methode liefert eine fertige Zeile ohne abschließenden Zeilenumbruch. */
|
|
181
|
+
export class Theme {
|
|
182
|
+
readonly values: ThemeValues;
|
|
183
|
+
readonly color: boolean;
|
|
184
|
+
readonly wrap: boolean;
|
|
185
|
+
#noticeShown = false;
|
|
186
|
+
|
|
187
|
+
constructor(values: ThemeValues, color: boolean, wrap = true) {
|
|
188
|
+
this.values = checked(values);
|
|
189
|
+
this.color = color;
|
|
190
|
+
this.wrap = wrap;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Theme aus clitheme; `color` wie BashLib, wenn nicht angegeben. */
|
|
194
|
+
static load(options: LoadOptions = {}): Theme {
|
|
195
|
+
return new Theme(
|
|
196
|
+
loadValues(options.command),
|
|
197
|
+
options.color ?? colorWanted(),
|
|
198
|
+
options.wrap ?? Deno.stdout.isTerminal(),
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Escape-Folge einer Rolle; leer, wenn das Theme keine Farbe dafür hat. */
|
|
203
|
+
code(role: Role): string {
|
|
204
|
+
const value = this.values[`THEME_COLOR_${role}`];
|
|
205
|
+
return typeof value === "string" ? value : "";
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Text in einer Rolle (themeStyle); ohne Farben ohne Escape-Folgen. */
|
|
209
|
+
style(text: string, role: Role): string {
|
|
210
|
+
const code = this.code(role);
|
|
211
|
+
const safe = guard(text);
|
|
212
|
+
return this.color && code ? `${code}${safe}${RESET}` : plain(safe);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Teil eines farbigen Texts (themeInline): Rolle, danach zurück zu `back`. */
|
|
216
|
+
inline(text: string, role: Role, back = ""): string {
|
|
217
|
+
const code = this.code(role);
|
|
218
|
+
const safe = guard(text);
|
|
219
|
+
return this.color && code ? `${code}${safe}${RESET}${back}` : safe;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Markierung wie [Maintainer] (themeMark). */
|
|
223
|
+
mark(text: string, back: Role = "DESC"): string {
|
|
224
|
+
return this.inline(text, "SERVER", this.color ? this.code(back) : "");
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Überschrift (printThemeHeading): Leerzeilen davor aus THEME_GROUP_SPACING; bricht um wie flow. */
|
|
228
|
+
heading(text: string): string {
|
|
229
|
+
const spacing = Math.max(0, Number(this.values.THEME_GROUP_SPACING) || 0);
|
|
230
|
+
const indent = this.values.THEME_INDENT_GROUP;
|
|
231
|
+
return "\n".repeat(spacing) + indent +
|
|
232
|
+
this.flow([{ text, role: "GROUP" }], indent.length, indent.length);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Zeile Beschriftung · Beschreibung (printThemeRow); `extra` verbreitert die erste Spalte. */
|
|
236
|
+
row(label: string, text: string, extra = 0, role: Role = "DESC"): string {
|
|
237
|
+
const width = Number(this.values.THEME_WIDTH_TARGET) + extra;
|
|
238
|
+
const gap = Math.max(1, Number(this.values.THEME_COLUMN_GAP) || 0);
|
|
239
|
+
const indent = this.values.THEME_INDENT_TARGET;
|
|
240
|
+
const length = [...plain(label)].length;
|
|
241
|
+
const head = indent + this.style(label, "TARGET");
|
|
242
|
+
const padding = length > width
|
|
243
|
+
? `\n${indent}${" ".repeat(width + gap)}`
|
|
244
|
+
: " ".repeat(width - length + gap);
|
|
245
|
+
return head + padding + this.style(text, role);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Zeile Bezeichnung · Wert (printThemeValue); der Wert in der Rolle VALUE. */
|
|
249
|
+
value(label: string, value: string): string {
|
|
250
|
+
return this.row(label, value, 0, "VALUE");
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Statuszeile „✓ Text“ (printThemeStatus) in der Rolle, etwa OK, WARN oder ERR. */
|
|
254
|
+
status(symbol: string, message: string, role: StatusRole): string {
|
|
255
|
+
return this.values.THEME_INDENT_GROUP +
|
|
256
|
+
this.style(`${symbol} ${message}`, Theme.statusRole(role));
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Rolle einer Statuskurzform: OK, WARN und ERR wie bei printThemeStatus. */
|
|
260
|
+
static statusRole(role: StatusRole): Role {
|
|
261
|
+
return role === "OK"
|
|
262
|
+
? "SUCCESS"
|
|
263
|
+
: role === "WARN"
|
|
264
|
+
? "WARNING"
|
|
265
|
+
: role === "ERR"
|
|
266
|
+
? "DANGER"
|
|
267
|
+
: role;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Größte Zeilenbreite: THEME_WIDTH_HELP, am Terminal höchstens dessen Spalten; ohne wrap unbegrenzt. */
|
|
271
|
+
lineWidth(): number {
|
|
272
|
+
if (!this.wrap) return Infinity;
|
|
273
|
+
const help = Number(this.values.THEME_WIDTH_HELP) || 120;
|
|
274
|
+
if (!Deno.stdout.isTerminal()) return help;
|
|
275
|
+
try {
|
|
276
|
+
return Math.min(help, Deno.consoleSize().columns);
|
|
277
|
+
} catch {
|
|
278
|
+
return help;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Teile ab Spalte `start` als Fließtext; was nicht mehr in die Zeile passt, kommt in
|
|
284
|
+
* Folgezeilen ab Spalte `follow`. Gebrochen wird an Leerzeichen; ein Wort, das auch in
|
|
285
|
+
* einer Folgezeile keinen Platz hat (etwa ein langer Pfad), wird nach „/“ oder „,“
|
|
286
|
+
* geteilt, notfalls mitten im Wort. Jede Zeile färbt gleiche Rollen am Stück.
|
|
287
|
+
*/
|
|
288
|
+
flow(pieces: Piece[], start: number, follow: number): string {
|
|
289
|
+
const width = this.lineWidth();
|
|
290
|
+
const room = Math.max(1, width - follow);
|
|
291
|
+
const lines: Word[][] = [[]];
|
|
292
|
+
let column = start;
|
|
293
|
+
for (const { text, role } of pieces) {
|
|
294
|
+
for (const word of plain(text).split(" ").filter(Boolean)) {
|
|
295
|
+
const parts = visible(word) > room ? splitWord(word, room) : [word];
|
|
296
|
+
parts.forEach((part, index) => {
|
|
297
|
+
const line = lines[lines.length - 1];
|
|
298
|
+
const glue = index > 0;
|
|
299
|
+
const need = (line.length && !glue ? 1 : 0) + visible(part);
|
|
300
|
+
if (line.length && column + need > width) {
|
|
301
|
+
lines.push([{ text: part, role, glue: false }]);
|
|
302
|
+
column = follow + visible(part);
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
line.push({ text: part, role, glue });
|
|
306
|
+
column += need;
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return lines.map((line) => this.#runs(line)).join(`\n${" ".repeat(follow)}`);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Wörter einer Zeile, gleiche Rollen am Stück gefärbt; geteilte Wörter ohne Leerzeichen. */
|
|
314
|
+
#runs(words: Word[]): string {
|
|
315
|
+
let text = "";
|
|
316
|
+
let run = "";
|
|
317
|
+
let role: Role | undefined;
|
|
318
|
+
const flush = () => {
|
|
319
|
+
text += role ? this.style(run, role) : run;
|
|
320
|
+
run = "";
|
|
321
|
+
};
|
|
322
|
+
words.forEach((word, index) => {
|
|
323
|
+
const gap = index === 0 || word.glue ? "" : " ";
|
|
324
|
+
if (index > 0 && word.role !== role) {
|
|
325
|
+
flush();
|
|
326
|
+
text += gap;
|
|
327
|
+
run = word.text;
|
|
328
|
+
} else run += gap + word.text;
|
|
329
|
+
role = word.role;
|
|
330
|
+
});
|
|
331
|
+
flush();
|
|
332
|
+
return text;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Prüfzeile „✓ Name Detail · Zusatz“: Zeichen in der Statusrolle, Name in TARGET auf
|
|
337
|
+
* `width` Zeichen aufgefüllt, Detail in `role`, Zusatz in HINT. Passt das nicht in eine
|
|
338
|
+
* Zeile, steht der Zusatz ohne „·“ in einer eigenen Zeile unter dem Detail, und zu langes
|
|
339
|
+
* Detail bricht um. Bleiben neben dem Namen keine 20 Spalten, beginnt das Detail in der
|
|
340
|
+
* Zeile darunter, eingerückt unter dem Namen.
|
|
341
|
+
*/
|
|
342
|
+
check(
|
|
343
|
+
symbol: string,
|
|
344
|
+
status: StatusRole,
|
|
345
|
+
name: string,
|
|
346
|
+
width: number,
|
|
347
|
+
detail: string,
|
|
348
|
+
role: Role = "DESC",
|
|
349
|
+
extra = "",
|
|
350
|
+
): string {
|
|
351
|
+
const indent = this.values.THEME_INDENT_GROUP;
|
|
352
|
+
const nameColumn = indent.length + visible(symbol) + 1;
|
|
353
|
+
const column = nameColumn + Math.max(width, visible(name)) + 3;
|
|
354
|
+
const narrow = this.lineWidth() - column < 20;
|
|
355
|
+
const start = narrow ? nameColumn + 2 : column;
|
|
356
|
+
const symbolText = `${indent}${this.style(symbol, Theme.statusRole(status))} `;
|
|
357
|
+
const head = narrow
|
|
358
|
+
? symbolText + this.flow([{ text: name, role: "TARGET" }], nameColumn, start) +
|
|
359
|
+
`\n${" ".repeat(start)}`
|
|
360
|
+
: symbolText + this.style(name, "TARGET") +
|
|
361
|
+
" ".repeat(column - nameColumn - visible(name));
|
|
362
|
+
const whole = start + visible(detail) + (extra ? 3 + visible(extra) : 0);
|
|
363
|
+
if (!extra || whole <= this.lineWidth()) {
|
|
364
|
+
const pieces: Piece[] = [{ text: detail, role }];
|
|
365
|
+
if (extra) pieces.push({ text: "·" }, { text: extra, role: "HINT" });
|
|
366
|
+
return head + this.flow(pieces, start, start);
|
|
367
|
+
}
|
|
368
|
+
return head + this.flow([{ text: detail, role }], start, start) + "\n" +
|
|
369
|
+
" ".repeat(start) + this.flow([{ text: extra, role: "HINT" }], start, start);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Handlungshinweis „→ Text“ in HINT, eingerückt mit THEME_INDENT_HINT oder `indent`;
|
|
374
|
+
* ein Befehl zum Kopieren steht ungebrochen in der Zeile darunter, in ACCENT.
|
|
375
|
+
*/
|
|
376
|
+
advice(
|
|
377
|
+
text: string,
|
|
378
|
+
command = "",
|
|
379
|
+
indent = this.values.THEME_INDENT_HINT,
|
|
380
|
+
): string {
|
|
381
|
+
const follow = indent.length + 2;
|
|
382
|
+
const advice = indent +
|
|
383
|
+
this.flow([{ text: `→ ${text}`, role: "HINT" }], indent.length, follow);
|
|
384
|
+
return command ? `${advice}\n${" ".repeat(follow)}${this.style(command, "ACCENT")}` : advice;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* --help-Ausgabe wie bei changelog, zum Ausgeben mit console.log: Leerzeile davor und
|
|
389
|
+
* danach, Optionen in den Spalten von row, Beschreibungen umbrochen nach THEME_WIDTH_HELP.
|
|
390
|
+
*/
|
|
391
|
+
help(spec: HelpSpec): string {
|
|
392
|
+
return formatHelp(this, spec);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Hinweiszeile (printThemeHint), etwa der nächste Befehl. */
|
|
396
|
+
hint(text: string): string {
|
|
397
|
+
return this.values.THEME_INDENT_HINT + this.style(text, "HINT");
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* Meldung von clitheme (THEME_NOTICE) einmal, wie themeNotice: erste Zeile mit ⚠,
|
|
402
|
+
* der Rest als Hinweis. Leer, wenn es keine gibt oder sie schon gezeigt wurde.
|
|
403
|
+
*/
|
|
404
|
+
notice(): string {
|
|
405
|
+
const notice = this.values.THEME_NOTICE;
|
|
406
|
+
if (!notice || this.#noticeShown) return "";
|
|
407
|
+
this.#noticeShown = true;
|
|
408
|
+
const [first, ...rest] = notice.split("\n");
|
|
409
|
+
return `${this.values.THEME_INDENT_GROUP}⚠ ${first}\n${this.values.THEME_INDENT_HINT}${
|
|
410
|
+
rest.join("\n")
|
|
411
|
+
}`;
|
|
412
|
+
}
|
|
413
|
+
}
|
cli_theme/export.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Aufgelöste Theme-Werte für Bash, Make und als JSON: THEME_*-Werte aus dem gewählten Theme.
|
|
2
|
+
Dazu der Pfad des Deno-Pakets @mmit/clitheme, das mit clitheme kommt (deno_module).
|
|
3
|
+
|
|
4
|
+
Gelesen wird über load_theme, mit denselben Regeln wie in Python; Bash und Make lesen die
|
|
5
|
+
Theme-Datei so nicht mehr selbst. Fehlt die Datei oder ist sie ungültig, gibt es keine Farben,
|
|
6
|
+
die Abstände der classic-Vorlage und THEME_NOTICE mit Befund und nächstem Schritt.
|
|
7
|
+
|
|
8
|
+
Das Ergebnis liegt im Cache unter ${XDG_CACHE_HOME:-~/.cache}/clitheme/. Der Dateiname ist
|
|
9
|
+
ein Hash über alles, was das Ergebnis ändert (Version, CLI_THEME, Stand der mit clitheme use
|
|
10
|
+
gespeicherten Wahl, Ort und Stand der Theme-Datei, Sprache); eine fertige Datei ändert sich nie
|
|
11
|
+
mehr.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import shlex
|
|
18
|
+
import stat
|
|
19
|
+
import time
|
|
20
|
+
from importlib.metadata import version
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from cli_theme.i18n import N_, _
|
|
24
|
+
from cli_theme.theme import (
|
|
25
|
+
PACKAGE,
|
|
26
|
+
THEME_DIR,
|
|
27
|
+
ThemeError,
|
|
28
|
+
_refuse_link,
|
|
29
|
+
config_dir,
|
|
30
|
+
fallback_theme,
|
|
31
|
+
load_theme,
|
|
32
|
+
selection_error,
|
|
33
|
+
selection_path,
|
|
34
|
+
source_path,
|
|
35
|
+
theme_name,
|
|
36
|
+
theme_origin,
|
|
37
|
+
write_file,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
# Variable je Farbrolle (Escape-Folge), wie BashLib und MakeLib sie nennen.
|
|
41
|
+
COLORS = (
|
|
42
|
+
("THEME_COLOR_GROUP", "head"),
|
|
43
|
+
("THEME_COLOR_TARGET", "key"),
|
|
44
|
+
("THEME_COLOR_DESC", "text"),
|
|
45
|
+
("THEME_COLOR_VALUE", "val"),
|
|
46
|
+
("THEME_COLOR_HINT", "hint"),
|
|
47
|
+
("THEME_COLOR_ACCENT", "acc"),
|
|
48
|
+
("THEME_COLOR_SUCCESS", "ok"),
|
|
49
|
+
("THEME_COLOR_WARNING", "warn"),
|
|
50
|
+
("THEME_COLOR_DANGER", "err"),
|
|
51
|
+
("THEME_COLOR_SERVER", "mark"),
|
|
52
|
+
)
|
|
53
|
+
# Einrückungen als Leerzeichen, die übrigen Abstände als Zahl.
|
|
54
|
+
INDENTS = (
|
|
55
|
+
("THEME_INDENT_GROUP", "i_head"),
|
|
56
|
+
("THEME_INDENT_TARGET", "i_row"),
|
|
57
|
+
("THEME_INDENT_HINT", "i_hint"),
|
|
58
|
+
)
|
|
59
|
+
NUMBERS = (
|
|
60
|
+
("THEME_WIDTH_TARGET", "w_key"),
|
|
61
|
+
("THEME_WIDTH_COLUMN", "w_col"),
|
|
62
|
+
("THEME_COLUMN_GAP", "gap"),
|
|
63
|
+
("THEME_WIDTH_HELP", "width"),
|
|
64
|
+
("THEME_GROUP_SPACING", "space"),
|
|
65
|
+
)
|
|
66
|
+
FORMATS = {"bash": ".sh", "make": ".mk", "json": ".json"}
|
|
67
|
+
# Was Sprache und Katalog der Texte in THEME_NOTICE und THEME_ORIGIN bestimmt.
|
|
68
|
+
LOCALE_VARIABLES = ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG", "CLI_THEME_LOCALE_DIR")
|
|
69
|
+
# Ältere Cache-Dateien eines Formats räumt das Anlegen einer neuen weg.
|
|
70
|
+
CACHE_LIFETIME = 24 * 60 * 60
|
|
71
|
+
# Für Make: # beginnt sonst einen Kommentar, ein Zeilenumbruch beendet die Zuweisung.
|
|
72
|
+
MAKE_HELPERS = "cli_theme_hash := \\#\ndefine cli_theme_newline\n\n\nendef\n"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def sgr(value: str) -> str:
|
|
76
|
+
"""Farbangabe des Themes als Escape-Folge: bold+11 → ESC[1;38;5;11m, dim → ESC[2m."""
|
|
77
|
+
effect, _, number = value.rpartition("+") if "+" in value else ("", "", value)
|
|
78
|
+
if number in ("bold", "dim"):
|
|
79
|
+
effect, number = number, ""
|
|
80
|
+
codes = [{"bold": "1", "dim": "2"}[effect]] if effect else []
|
|
81
|
+
if number:
|
|
82
|
+
codes.append(f"38;5;{int(number)}")
|
|
83
|
+
return f"\x1b[{';'.join(codes)}m" if codes else ""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def theme_values() -> dict[str, str]:
|
|
87
|
+
"""THEME_*-Werte des gewählten Themes; scheitert nie an der Konfiguration."""
|
|
88
|
+
# Ohne CLI_THEME scheitert theme_name nie; ein ungültiger CLI_THEME erscheint wörtlich.
|
|
89
|
+
selected = os.environ.get("CLI_THEME", "")
|
|
90
|
+
values = {
|
|
91
|
+
"THEME_NAME": selected or theme_name(),
|
|
92
|
+
"THEME_SOURCE": "",
|
|
93
|
+
"THEME_ORIGIN": _(theme_origin()),
|
|
94
|
+
"THEME_NOTICE": "",
|
|
95
|
+
}
|
|
96
|
+
try:
|
|
97
|
+
values["THEME_SOURCE"] = str(source_path())
|
|
98
|
+
theme = load_theme()
|
|
99
|
+
if not theme.found:
|
|
100
|
+
finding = _(N_("Theme file missing: {path}")).format(path=theme.path)
|
|
101
|
+
values["THEME_NOTICE"] = f"{finding}\nclitheme install"
|
|
102
|
+
elif theme.legacy:
|
|
103
|
+
finding = _(N_("Theme file still in the old folder {folder}"))
|
|
104
|
+
values["THEME_NOTICE"] = f"{finding.format(folder=theme.path.parent)}\nclitheme install"
|
|
105
|
+
except (ThemeError, OSError) as error:
|
|
106
|
+
theme = fallback_theme()
|
|
107
|
+
values["THEME_NOTICE"] = f"{error}\nclitheme show"
|
|
108
|
+
# Eine unbrauchbare gespeicherte Wahl ist die Ursache für alles Weitere; ihr Befund geht vor.
|
|
109
|
+
if (damaged := selection_error()) is not None:
|
|
110
|
+
values["THEME_NOTICE"] = f"{damaged}\nclitheme list"
|
|
111
|
+
for name, role in COLORS:
|
|
112
|
+
values[name] = sgr(theme.colors[role])
|
|
113
|
+
for name, key in INDENTS:
|
|
114
|
+
values[name] = " " * theme.spacing[key]
|
|
115
|
+
for name, key in NUMBERS:
|
|
116
|
+
values[name] = str(theme.spacing[key])
|
|
117
|
+
return values
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def bash_text(values: dict[str, str]) -> str:
|
|
121
|
+
"""Zuweisungen für eval in Bash; shlex quotet jeden Wert, eval führt so nichts aus."""
|
|
122
|
+
lines = [f"{name}={shlex.quote(value)}" for name, value in values.items()]
|
|
123
|
+
return "# clitheme export --bash\n" + "\n".join(lines) + "\n"
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def make_value(value: str) -> str:
|
|
127
|
+
"""Wert für eine :=-Zuweisung: $ verdoppelt, # und Zeilenumbruch über Hilfsvariablen;
|
|
128
|
+
$() vorn und hinten hält Leerzeichen am Rand und einen Backslash am Ende."""
|
|
129
|
+
value = value.replace("$", "$$").replace("#", "$(cli_theme_hash)")
|
|
130
|
+
return f"$(){value.replace(chr(10), '$(cli_theme_newline)')}$()"
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def make_text(values: dict[str, str]) -> str:
|
|
134
|
+
""".mk-Datei mit den THEME_*-Variablen, zum Einbinden mit -include."""
|
|
135
|
+
lines = [f"{name} := {make_value(value)}" for name, value in values.items()]
|
|
136
|
+
return "# clitheme export --make\n" + MAKE_HELPERS + "\n".join(lines) + "\n"
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def json_text(values: dict[str, str]) -> str:
|
|
140
|
+
"""Ein JSON-Objekt für andere Sprachen (etwa Deno): Breiten und Abstände als Zahl, alles
|
|
141
|
+
andere als String; json quotet Steuerzeichen, Anführungszeichen und Backslash."""
|
|
142
|
+
numbers = {name for name, _ in NUMBERS}
|
|
143
|
+
data = {name: int(value) if name in numbers else value for name, value in values.items()}
|
|
144
|
+
return json.dumps(data, indent=2) + "\n"
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
# Deno-Paket @mmit/clitheme (Ordner deno/ im Paket, übernommen aus ProjectTools).
|
|
148
|
+
DENO_MODULE = Path(__file__).parent / "deno" / "mod.ts"
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def deno_module() -> Path:
|
|
152
|
+
"""Pfad von mod.ts des Deno-Pakets in dieser Installation; ThemeError, wenn es fehlt."""
|
|
153
|
+
if not DENO_MODULE.is_file():
|
|
154
|
+
raise ThemeError("deno_missing", N_("Deno package missing: {path}"), path=DENO_MODULE)
|
|
155
|
+
return DENO_MODULE
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# Text je Format für die Cache-Datei.
|
|
159
|
+
RENDER = {"bash": bash_text, "make": make_text, "json": json_text}
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def cache_dir() -> Path:
|
|
163
|
+
"""$XDG_CACHE_HOME/clitheme, sonst ~/.cache/clitheme; ein relativer Ort gilt nicht."""
|
|
164
|
+
base = os.environ.get("XDG_CACHE_HOME", "")
|
|
165
|
+
root = Path(base) if os.path.isabs(base) else Path.home() / ".cache"
|
|
166
|
+
return root / THEME_DIR
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _state(path: Path) -> str:
|
|
170
|
+
"""Stand von path ohne Link-Folge: Art, Größe, Zeiten und Inode, oder dass es fehlt."""
|
|
171
|
+
try:
|
|
172
|
+
info = os.lstat(path)
|
|
173
|
+
except OSError as error:
|
|
174
|
+
return f"{path}: {error.errno}"
|
|
175
|
+
fields = (info.st_mode, info.st_size, info.st_mtime_ns, info.st_ctime_ns, info.st_ino)
|
|
176
|
+
return f"{path}: {fields}"
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def cache_key(form: str) -> str:
|
|
180
|
+
"""Hash über alles, was das Ergebnis ändert; die Theme-Datei zählt mit ihrem Stand, der
|
|
181
|
+
neue Ordner auch, damit sein Anlegen den Umzug aus dem alten sichtbar macht, und die
|
|
182
|
+
gespeicherte Wahl, damit clitheme use den nächsten Aufruf neu rechnen lässt."""
|
|
183
|
+
files = f"{_state(config_dir())}\n{_state(selection_path())}"
|
|
184
|
+
try:
|
|
185
|
+
path = source_path()
|
|
186
|
+
files += f"\n{_state(path.parent)}\n{_state(path)}"
|
|
187
|
+
except ThemeError:
|
|
188
|
+
pass
|
|
189
|
+
locale = [f"{name}={os.environ.get(name, '')}" for name in LOCALE_VARIABLES]
|
|
190
|
+
parts = [form, version(PACKAGE), f"CLI_THEME={os.environ.get('CLI_THEME', '')}", files, *locale]
|
|
191
|
+
return hashlib.sha256("\n".join(parts).encode("utf-8", "surrogateescape")).hexdigest()[:24]
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _cached(path: Path) -> bool:
|
|
195
|
+
"""Liegt unter path eine fertige Cache-Datei (regulär, kein Link)?"""
|
|
196
|
+
try:
|
|
197
|
+
return stat.S_ISREG(os.lstat(path).st_mode)
|
|
198
|
+
except OSError:
|
|
199
|
+
return False
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _write(path: Path, content: str) -> None:
|
|
203
|
+
"""Schreibt content über write_file, nie halb; danach fallen alte Dateien desselben
|
|
204
|
+
Formats weg."""
|
|
205
|
+
directory = path.parent
|
|
206
|
+
_refuse_link(directory)
|
|
207
|
+
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
208
|
+
write_file(path, content)
|
|
209
|
+
limit = time.time() - CACHE_LIFETIME
|
|
210
|
+
for old in directory.glob(f"*{path.suffix}"):
|
|
211
|
+
if old != path and _cached(old) and old.stat().st_mtime < limit:
|
|
212
|
+
old.unlink(missing_ok=True)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def export(form: str) -> Path:
|
|
216
|
+
"""Cache-Datei für form (bash, make oder json); legt sie nur an, wenn sie fehlt."""
|
|
217
|
+
path = cache_dir() / f"{cache_key(form)}{FORMATS[form]}"
|
|
218
|
+
if not _cached(path):
|
|
219
|
+
values = theme_values()
|
|
220
|
+
_write(path, RENDER[form](values))
|
|
221
|
+
return path
|
cli_theme/i18n.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Übersetzung der sichtbaren Texte; Basissprache Englisch, Deutsch aus dem Katalog."""
|
|
2
|
+
|
|
3
|
+
import gettext
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
# CLI_THEME_LOCALE_DIR nennt einen anderen Katalogordner; die Tests zeigen damit auf einen
|
|
8
|
+
# eigenen und hängen nicht davon ab, ob im Quellbaum eine .mo liegt.
|
|
9
|
+
LOCALES = Path(os.environ.get("CLI_THEME_LOCALE_DIR") or Path(__file__).parent / "locales")
|
|
10
|
+
DOMAIN = "cli_theme"
|
|
11
|
+
|
|
12
|
+
# Sprache wie üblich aus LANGUAGE, LC_ALL, LC_MESSAGES oder LANG; ohne Katalog Englisch.
|
|
13
|
+
_ = gettext.translation(DOMAIN, localedir=LOCALES, fallback=True).gettext
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def N_(text: str) -> str:
|
|
17
|
+
"""Markiert text für den Katalog; übersetzt wird erst bei der Ausgabe."""
|
|
18
|
+
return text
|
|
Binary file
|