peekfetch 0.0.0-stage → 0.1.1
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.
- package/LICENSE +21 -0
- package/README.md +175 -2
- package/THIRD_PARTY_NOTICES.md +29 -0
- package/bin/peekfetch.js +14 -0
- package/package.json +44 -4
- package/src/ansi.js +89 -0
- package/src/cache.js +52 -0
- package/src/cli.js +91 -0
- package/src/config.js +65 -0
- package/src/context.js +113 -0
- package/src/exec.js +93 -0
- package/src/format.js +95 -0
- package/src/index.js +137 -0
- package/src/logos/index.js +44 -0
- package/src/logos/logos.json +1 -0
- package/src/modules/desktop.js +152 -0
- package/src/modules/hardware.js +156 -0
- package/src/modules/index.js +41 -0
- package/src/modules/packages.js +96 -0
- package/src/modules/system.js +131 -0
- package/src/modules/terminal.js +206 -0
- package/src/parsers.js +294 -0
- package/src/render.js +113 -0
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { join, basename } from 'node:path';
|
|
2
|
+
import { run, readText, which } from '../exec.js';
|
|
3
|
+
import { parseShellVersion, parseConfLines, stripJsonComments } from '../parsers.js';
|
|
4
|
+
|
|
5
|
+
const SHELLS = new Set([
|
|
6
|
+
'bash', 'zsh', 'fish', 'nu', 'nushell', 'sh', 'dash', 'ash', 'ksh', 'mksh', 'oksh', 'loksh',
|
|
7
|
+
'tcsh', 'csh', 'elvish', 'xonsh', 'ion', 'osh', 'ysh', 'yash', 'pwsh', 'powershell', 'cmd', 'murex',
|
|
8
|
+
]);
|
|
9
|
+
|
|
10
|
+
// Processes that sit between us and the terminal and should be walked past.
|
|
11
|
+
const WRAPPERS = new Set(['node', 'nodejs', 'npm', 'npx', 'pnpm', 'yarn', 'bun', 'deno', 'sudo', 'doas', 'su', 'env', 'time', 'peekfetch', 'login', 'script', 'nix', 'direnv']);
|
|
12
|
+
const STOPS = new Set(['launchd', 'init', 'systemd', 'kernel_task', 'explorer', 'services', 'wininit', 'svchost']);
|
|
13
|
+
|
|
14
|
+
const normalizeName = (n) => basename(String(n ?? '')).replace(/^-/, '').replace(/\.exe$/i, '').toLowerCase();
|
|
15
|
+
|
|
16
|
+
/** The interactive shell that launched us (not just $SHELL, which is only the login shell). */
|
|
17
|
+
function detectShell(ctx) {
|
|
18
|
+
return ctx.once('shell', async () => {
|
|
19
|
+
const chain = (await ctx.ancestors()) ?? [];
|
|
20
|
+
const shells = chain.filter((p) => SHELLS.has(normalizeName(p.name)));
|
|
21
|
+
// `npx peekfetch` runs us through `sh -c`, so prefer the first shell that is not plain sh.
|
|
22
|
+
const pick = shells.find((p) => !['sh', 'dash'].includes(normalizeName(p.name))) ?? shells[0];
|
|
23
|
+
let name = pick ? normalizeName(pick.name) : null;
|
|
24
|
+
let path = pick?.path?.startsWith('/') ? pick.path.replace(/^-/, '') : null;
|
|
25
|
+
if (!name && ctx.env.SHELL) {
|
|
26
|
+
name = normalizeName(ctx.env.SHELL);
|
|
27
|
+
path = ctx.env.SHELL;
|
|
28
|
+
}
|
|
29
|
+
if (!name && ctx.platform === 'win32') name = ctx.env.PSModulePath ? 'powershell' : 'cmd';
|
|
30
|
+
if (!name) return null;
|
|
31
|
+
if (!path && ctx.env.SHELL && normalizeName(ctx.env.SHELL) === name) path = ctx.env.SHELL;
|
|
32
|
+
path ??= await which(name);
|
|
33
|
+
return { name, path };
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Terminal emulator: TERM_PROGRAM and friends first, then walk up the process tree. */
|
|
38
|
+
function detectTerminal(ctx) {
|
|
39
|
+
return ctx.once('terminal', async () => {
|
|
40
|
+
const env = ctx.env;
|
|
41
|
+
const named = (id, name, version = env.TERM_PROGRAM_VERSION) => ({ id, name, version: version || null });
|
|
42
|
+
|
|
43
|
+
if (env.TMUX || env.TERM_PROGRAM === 'tmux') return named('tmux', 'tmux');
|
|
44
|
+
if (env.STY) return named('screen', 'GNU Screen', null);
|
|
45
|
+
|
|
46
|
+
const PROGRAMS = {
|
|
47
|
+
'iTerm.app': 'iTerm2',
|
|
48
|
+
Apple_Terminal: 'Apple Terminal',
|
|
49
|
+
vscode: 'VS Code',
|
|
50
|
+
WezTerm: 'WezTerm',
|
|
51
|
+
ghostty: 'Ghostty',
|
|
52
|
+
Hyper: 'Hyper',
|
|
53
|
+
Tabby: 'Tabby',
|
|
54
|
+
WarpTerminal: 'Warp',
|
|
55
|
+
rio: 'Rio',
|
|
56
|
+
zed: 'Zed',
|
|
57
|
+
kitty: 'kitty',
|
|
58
|
+
alacritty: 'Alacritty',
|
|
59
|
+
};
|
|
60
|
+
if (env.TERM_PROGRAM && PROGRAMS[env.TERM_PROGRAM]) return named(env.TERM_PROGRAM, PROGRAMS[env.TERM_PROGRAM]);
|
|
61
|
+
|
|
62
|
+
if (env.WT_SESSION) return named('windows-terminal', 'Windows Terminal', null);
|
|
63
|
+
if (env.KITTY_WINDOW_ID || env.TERM === 'xterm-kitty') return named('kitty', 'kitty', null);
|
|
64
|
+
if (env.ALACRITTY_WINDOW_ID || env.ALACRITTY_SOCKET || env.ALACRITTY_LOG) return named('alacritty', 'Alacritty', null);
|
|
65
|
+
if (env.GHOSTTY_RESOURCES_DIR) return named('ghostty', 'Ghostty', null);
|
|
66
|
+
if (env.WEZTERM_PANE) return named('WezTerm', 'WezTerm', null);
|
|
67
|
+
if (env.KONSOLE_VERSION) return named('konsole', 'Konsole', null);
|
|
68
|
+
if (env.TERMINATOR_UUID) return named('terminator', 'Terminator', null);
|
|
69
|
+
if (env.TILIX_ID) return named('tilix', 'Tilix', null);
|
|
70
|
+
if (env.TERMUX_VERSION) return named('termux', 'Termux', env.TERMUX_VERSION);
|
|
71
|
+
if (env.GNOME_TERMINAL_SCREEN || env.GNOME_TERMINAL_SERVICE) return named('gnome-terminal', 'GNOME Terminal', null);
|
|
72
|
+
if (env.TERM_PROGRAM) return named(env.TERM_PROGRAM, env.TERM_PROGRAM.replace(/\.app$/, ''));
|
|
73
|
+
|
|
74
|
+
// Walk the process tree past shells and wrappers; the first other ancestor is the terminal.
|
|
75
|
+
const PRETTY = {
|
|
76
|
+
'gnome-terminal-server': 'GNOME Terminal', 'gnome-terminal-': 'GNOME Terminal', konsole: 'Konsole',
|
|
77
|
+
'xfce4-terminal': 'Xfce Terminal', 'mate-terminal': 'MATE Terminal', 'lxterminal': 'LXTerminal',
|
|
78
|
+
'qterminal': 'QTerminal', terminal: 'Terminal', urxvtd: 'urxvt', 'kgx': 'GNOME Console', 'ptyxis-agent': 'Ptyxis',
|
|
79
|
+
foot: 'foot', footclient: 'foot', 'windowsterminal': 'Windows Terminal', conhost: 'Console Host', 'openconsole': 'Windows Terminal',
|
|
80
|
+
code: 'VS Code', 'code helper': 'VS Code', cursor: 'Cursor',
|
|
81
|
+
};
|
|
82
|
+
for (const p of (await ctx.ancestors()) ?? []) {
|
|
83
|
+
const n = normalizeName(p.name);
|
|
84
|
+
if (SHELLS.has(n) || WRAPPERS.has(n)) continue;
|
|
85
|
+
if (STOPS.has(n)) break;
|
|
86
|
+
if (n.startsWith('sshd')) return named('ssh', `SSH${env.SSH_TTY ? ` (${env.SSH_TTY})` : ''}`, null);
|
|
87
|
+
return named(n, PRETTY[n] ?? basename(p.name).replace(/^-/, '').replace(/\.exe$/i, ''), null);
|
|
88
|
+
}
|
|
89
|
+
if (env.SSH_CONNECTION) return named('ssh', 'SSH', null);
|
|
90
|
+
return null;
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Font configured in the terminal emulator. Each terminal stores it somewhere different. */
|
|
95
|
+
async function detectFont(ctx, term) {
|
|
96
|
+
const home = ctx.home;
|
|
97
|
+
const xdg = ctx.env.XDG_CONFIG_HOME ?? join(home, '.config');
|
|
98
|
+
const firstFile = async (paths) => {
|
|
99
|
+
for (const p of paths) {
|
|
100
|
+
const text = await readText(p);
|
|
101
|
+
if (text) return text;
|
|
102
|
+
}
|
|
103
|
+
return null;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
switch (term.id) {
|
|
107
|
+
case 'Apple_Terminal': {
|
|
108
|
+
const out = await run('osascript', ['-e', 'tell application "Terminal" to get {font name, font size} of window frontmost'], { timeout: 1500 });
|
|
109
|
+
const m = /^(.+),\s*(\d+)/.exec(out?.trim() ?? '');
|
|
110
|
+
return m ? `${m[1]} ${m[2]}` : null;
|
|
111
|
+
}
|
|
112
|
+
case 'iTerm.app': {
|
|
113
|
+
const plist = join(home, 'Library/Preferences/com.googlecode.iterm2.plist');
|
|
114
|
+
const json = await run('plutil', ['-extract', 'New Bookmarks', 'json', '-o', '-', plist]);
|
|
115
|
+
try {
|
|
116
|
+
const profiles = JSON.parse(json);
|
|
117
|
+
const p = profiles.find((x) => x.Name === ctx.env.ITERM_PROFILE) ?? profiles[0];
|
|
118
|
+
return p?.['Normal Font'] ?? null;
|
|
119
|
+
} catch {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
case 'kitty': {
|
|
124
|
+
const conf = parseConfLines(await readText(join(xdg, 'kitty/kitty.conf')), /\s+/);
|
|
125
|
+
return `${conf.font_family ?? 'monospace'} ${conf.font_size ?? '11.0'}`;
|
|
126
|
+
}
|
|
127
|
+
case 'alacritty': {
|
|
128
|
+
const toml = await firstFile([join(xdg, 'alacritty/alacritty.toml'), join(home, '.alacritty.toml')]);
|
|
129
|
+
if (!toml) return null;
|
|
130
|
+
const family = /family\s*=\s*"([^"]+)"/.exec(toml)?.[1];
|
|
131
|
+
const size = /^\s*size\s*=\s*([\d.]+)/m.exec(toml)?.[1];
|
|
132
|
+
return family ? `${family}${size ? ` ${size}` : ''}` : null;
|
|
133
|
+
}
|
|
134
|
+
case 'ghostty': {
|
|
135
|
+
const text = await firstFile([join(xdg, 'ghostty/config'), join(home, 'Library/Application Support/com.mitchellh.ghostty/config')]);
|
|
136
|
+
const conf = parseConfLines(text);
|
|
137
|
+
return `${conf['font-family'] ?? 'JetBrains Mono'} ${conf['font-size'] ?? '13'}`;
|
|
138
|
+
}
|
|
139
|
+
case 'WezTerm': {
|
|
140
|
+
const lua = await firstFile([join(home, '.wezterm.lua'), join(xdg, 'wezterm/wezterm.lua')]);
|
|
141
|
+
if (!lua) return 'JetBrains Mono 12';
|
|
142
|
+
const family = /wezterm\.font(?:_with_fallback)?\s*\(\s*\{?\s*(?:family\s*=\s*)?["']([^"']+)/.exec(lua)?.[1];
|
|
143
|
+
const size = /font_size\s*=\s*([\d.]+)/.exec(lua)?.[1];
|
|
144
|
+
return `${family ?? 'JetBrains Mono'} ${size ?? '12'}`;
|
|
145
|
+
}
|
|
146
|
+
case 'foot': {
|
|
147
|
+
const conf = parseConfLines(await readText(join(xdg, 'foot/foot.ini')));
|
|
148
|
+
return conf.font ?? 'monospace 8';
|
|
149
|
+
}
|
|
150
|
+
case 'vscode': {
|
|
151
|
+
const dir = { darwin: join(home, 'Library/Application Support/Code/User'), win32: join(ctx.env.APPDATA ?? '', 'Code/User') }[ctx.platform] ?? join(xdg, 'Code/User');
|
|
152
|
+
const text = await readText(join(dir, 'settings.json'));
|
|
153
|
+
try {
|
|
154
|
+
const s = JSON.parse(stripJsonComments(text ?? '{}'));
|
|
155
|
+
return s['terminal.integrated.fontFamily'] ?? s['editor.fontFamily'] ?? null;
|
|
156
|
+
} catch {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
case 'windows-terminal': {
|
|
161
|
+
const text = await readText(join(ctx.env.LOCALAPPDATA ?? '', 'Packages/Microsoft.WindowsTerminal_8wekyb3d8bbwe/LocalState/settings.json'));
|
|
162
|
+
return /"face"\s*:\s*"([^"]+)"/.exec(text ?? '')?.[1] ?? 'Cascadia Mono';
|
|
163
|
+
}
|
|
164
|
+
case 'gnome-terminal':
|
|
165
|
+
case 'gnome-terminal-server': {
|
|
166
|
+
const out = await run('gsettings', ['get', 'org.gnome.desktop.interface', 'monospace-font-name']);
|
|
167
|
+
return out?.trim().replace(/^'|'$/g, '') || null;
|
|
168
|
+
}
|
|
169
|
+
default:
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export default [
|
|
175
|
+
{
|
|
176
|
+
key: 'shell',
|
|
177
|
+
label: 'Shell',
|
|
178
|
+
async get(ctx) {
|
|
179
|
+
const shell = await detectShell(ctx);
|
|
180
|
+
if (!shell) return null;
|
|
181
|
+
let version = null;
|
|
182
|
+
// sh/dash have no --version flag (and macOS's /bin/sh would answer as bash 3.2).
|
|
183
|
+
if (shell.path && !['sh', 'dash', 'ash', 'cmd', 'powershell'].includes(shell.name)) {
|
|
184
|
+
version = parseShellVersion(shell.name, await run(shell.path, ['--version'], { timeout: 1000 }));
|
|
185
|
+
}
|
|
186
|
+
return { text: version ? `${shell.name} ${version}` : shell.name, data: { name: shell.name, version, path: shell.path } };
|
|
187
|
+
},
|
|
188
|
+
},
|
|
189
|
+
{
|
|
190
|
+
key: 'terminal',
|
|
191
|
+
label: 'Terminal',
|
|
192
|
+
async get(ctx) {
|
|
193
|
+
const term = await detectTerminal(ctx);
|
|
194
|
+
if (!term) return null;
|
|
195
|
+
return { text: term.version ? `${term.name} ${term.version}` : term.name, data: term };
|
|
196
|
+
},
|
|
197
|
+
},
|
|
198
|
+
{
|
|
199
|
+
key: 'font',
|
|
200
|
+
label: 'Terminal Font',
|
|
201
|
+
async get(ctx) {
|
|
202
|
+
const term = await detectTerminal(ctx);
|
|
203
|
+
return term ? detectFont(ctx, term) : null;
|
|
204
|
+
},
|
|
205
|
+
},
|
|
206
|
+
];
|
package/src/parsers.js
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
// Pure parsers for the text that system tools print.
|
|
2
|
+
// Each one takes a string and returns data, so they can be tested against fixtures.
|
|
3
|
+
|
|
4
|
+
/** /etc/os-release, /etc/lsb-release: KEY=value with optional quotes. */
|
|
5
|
+
export function parseOsRelease(text) {
|
|
6
|
+
const out = {};
|
|
7
|
+
for (const line of String(text ?? '').split('\n')) {
|
|
8
|
+
const m = /^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/.exec(line);
|
|
9
|
+
if (!m) continue;
|
|
10
|
+
let v = m[2].trim();
|
|
11
|
+
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1);
|
|
12
|
+
out[m[1]] = v.replace(/\\(["'$`\\])/g, '$1');
|
|
13
|
+
}
|
|
14
|
+
return out;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** macOS `sw_vers`. */
|
|
18
|
+
export function parseSwVers(text) {
|
|
19
|
+
const get = (k) => new RegExp(`^${k}:\\s*(.+)$`, 'm').exec(text ?? '')?.[1]?.trim() ?? null;
|
|
20
|
+
return { name: get('ProductName'), version: get('ProductVersion'), build: get('BuildVersion') };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const MACOS_NAMES = [
|
|
24
|
+
['26', 'Tahoe'],
|
|
25
|
+
['15', 'Sequoia'],
|
|
26
|
+
['14', 'Sonoma'],
|
|
27
|
+
['13', 'Ventura'],
|
|
28
|
+
['12', 'Monterey'],
|
|
29
|
+
['11', 'Big Sur'],
|
|
30
|
+
['10.15', 'Catalina'],
|
|
31
|
+
['10.14', 'Mojave'],
|
|
32
|
+
['10.13', 'High Sierra'],
|
|
33
|
+
['10.12', 'Sierra'],
|
|
34
|
+
['10.11', 'El Capitan'],
|
|
35
|
+
['10.10', 'Yosemite'],
|
|
36
|
+
];
|
|
37
|
+
|
|
38
|
+
export function macosCodename(version) {
|
|
39
|
+
if (!version) return null;
|
|
40
|
+
const hit = MACOS_NAMES.find(([v]) => version === v || version.startsWith(v + '.'));
|
|
41
|
+
return hit ? hit[1] : null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* macOS `vm_stat`. Returns the page size and page counts.
|
|
46
|
+
*
|
|
47
|
+
* neofetch multiplies page counts by 4 KiB. Apple Silicon uses 16 KiB pages, so neofetch
|
|
48
|
+
* under-reports used memory by 4x there. We read the page size from the header instead.
|
|
49
|
+
*/
|
|
50
|
+
export function parseVmStat(text) {
|
|
51
|
+
const str = String(text ?? '');
|
|
52
|
+
const pageSize = Number(/page size of (\d+) bytes/.exec(str)?.[1] ?? 4096);
|
|
53
|
+
const pages = {};
|
|
54
|
+
for (const line of str.split('\n')) {
|
|
55
|
+
const m = /^"?([^":]+)"?:\s+(\d+)\.?\s*$/.exec(line.trim());
|
|
56
|
+
if (m) pages[m[1].trim()] = Number(m[2]);
|
|
57
|
+
}
|
|
58
|
+
return { pageSize, pages };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* "Memory Used" as Activity Monitor shows it: app memory + wired + compressed.
|
|
63
|
+
* App memory = anonymous (internal) pages - purgeable pages.
|
|
64
|
+
*/
|
|
65
|
+
export function macMemoryUsed({ pageSize, pages }) {
|
|
66
|
+
const p = (k) => pages[k] ?? 0;
|
|
67
|
+
const anonymous = pages['Anonymous pages'] ?? p('Pages active') + p('Pages inactive') + p('Pages speculative') - p('File-backed pages');
|
|
68
|
+
const used = anonymous - p('Pages purgeable') + p('Pages wired down') + p('Pages occupied by compressor');
|
|
69
|
+
return Math.max(0, used) * pageSize;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Linux /proc/meminfo, values converted to bytes. */
|
|
73
|
+
export function parseMeminfo(text) {
|
|
74
|
+
const out = {};
|
|
75
|
+
for (const line of String(text ?? '').split('\n')) {
|
|
76
|
+
const m = /^(\w+(?:\(\w+\))?):\s+(\d+)(?:\s+kB)?/.exec(line);
|
|
77
|
+
if (m) out[m[1]] = Number(m[2]) * 1024;
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Linux used memory: MemTotal - MemAvailable (what `free` and the kernel recommend). */
|
|
83
|
+
export function linuxMemory(meminfo) {
|
|
84
|
+
const total = meminfo.MemTotal;
|
|
85
|
+
if (!total) return null;
|
|
86
|
+
const available =
|
|
87
|
+
meminfo.MemAvailable ?? (meminfo.MemFree ?? 0) + (meminfo.Buffers ?? 0) + (meminfo.Cached ?? 0) + (meminfo.SReclaimable ?? 0) - (meminfo.Shmem ?? 0);
|
|
88
|
+
return { total, used: Math.max(0, total - available) };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** macOS `sysctl -n vm.swapusage`: "total = 2048.00M used = 1035.25M free = 1012.75M (encrypted)". */
|
|
92
|
+
export function parseSwapUsage(text) {
|
|
93
|
+
const unit = { K: 1024, M: 1024 ** 2, G: 1024 ** 3, T: 1024 ** 4 };
|
|
94
|
+
const get = (k) => {
|
|
95
|
+
const m = new RegExp(`${k}\\s*=\\s*([\\d.]+)([KMGT])`).exec(text ?? '');
|
|
96
|
+
return m ? Number(m[1]) * unit[m[2]] : null;
|
|
97
|
+
};
|
|
98
|
+
const total = get('total');
|
|
99
|
+
const used = get('used');
|
|
100
|
+
return total === null || used === null ? null : { total, used };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** macOS `pmset -g batt`. */
|
|
104
|
+
export function parsePmset(text) {
|
|
105
|
+
const m = /(\d+)%;\s*([^;\n]+)(?:;\s*([^\n]*))?/.exec(text ?? '');
|
|
106
|
+
if (!m) return null;
|
|
107
|
+
const state = m[2].trim();
|
|
108
|
+
const time = /(\d+:\d+) remaining/.exec(m[3] ?? '')?.[1] ?? null;
|
|
109
|
+
return { percent: Number(m[1]), state, remaining: time };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** `lspci -mm` lines for display controllers -> [{ vendor, device }]. */
|
|
113
|
+
export function parseLspci(text) {
|
|
114
|
+
const out = [];
|
|
115
|
+
for (const line of String(text ?? '').split('\n')) {
|
|
116
|
+
const fields = [...line.matchAll(/"([^"]*)"/g)].map((m) => m[1]);
|
|
117
|
+
if (fields.length < 3) continue;
|
|
118
|
+
if (!/VGA|3D|Display/i.test(fields[0])) continue;
|
|
119
|
+
out.push({ vendor: fields[1], device: fields[2] });
|
|
120
|
+
}
|
|
121
|
+
return out;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** `xrandr --current`: active modes are marked with `*`. */
|
|
125
|
+
export function parseXrandr(text) {
|
|
126
|
+
const out = [];
|
|
127
|
+
for (const line of String(text ?? '').split('\n')) {
|
|
128
|
+
const m = /^\s+(\d+x\d+)\s+(.*)$/.exec(line);
|
|
129
|
+
if (!m || !m[2].includes('*')) continue;
|
|
130
|
+
const rate = /([\d.]+)\*/.exec(m[2])?.[1];
|
|
131
|
+
out.push(rate ? `${m[1]} @ ${Math.round(Number(rate))}Hz` : m[1]);
|
|
132
|
+
}
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** `system_profiler SPDisplaysDataType -json`. */
|
|
137
|
+
export function parseSystemProfilerDisplays(json) {
|
|
138
|
+
let data;
|
|
139
|
+
try {
|
|
140
|
+
data = typeof json === 'string' ? JSON.parse(json) : json;
|
|
141
|
+
} catch {
|
|
142
|
+
return { gpus: [], displays: [] };
|
|
143
|
+
}
|
|
144
|
+
const gpus = [];
|
|
145
|
+
const displays = [];
|
|
146
|
+
for (const gpu of data?.SPDisplaysDataType ?? []) {
|
|
147
|
+
const name = gpu.sppci_model ?? gpu._name;
|
|
148
|
+
if (name) gpus.push({ name, cores: gpu.sppci_cores ? Number(gpu.sppci_cores) : null });
|
|
149
|
+
for (const d of gpu.spdisplays_ndrvs ?? []) {
|
|
150
|
+
const res = /(\d+)\s*x\s*(\d+)(?:\s*@\s*([\d.]+)\s*Hz)?/.exec(d._spdisplays_resolution ?? d._spdisplays_pixels ?? '');
|
|
151
|
+
if (!res) continue;
|
|
152
|
+
displays.push({
|
|
153
|
+
name: d._name ?? null,
|
|
154
|
+
width: Number(res[1]),
|
|
155
|
+
height: Number(res[2]),
|
|
156
|
+
refresh: res[3] ? Math.round(Number(res[3])) : null,
|
|
157
|
+
main: d.spdisplays_main === 'spdisplays_yes',
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return { gpus, displays };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** `ioreg -rc IOAccelerator -d1`: GPU model and core count on Apple Silicon. */
|
|
165
|
+
export function parseIoregGpu(text) {
|
|
166
|
+
const out = [];
|
|
167
|
+
for (const block of String(text ?? '').split(/\n(?=\+-o )/)) {
|
|
168
|
+
const model = /"model" = (?:<)?"([^"]+)"/.exec(block)?.[1];
|
|
169
|
+
if (!model) continue;
|
|
170
|
+
const cores = /"gpu-core-count" = (\d+)/.exec(block)?.[1];
|
|
171
|
+
out.push({ name: model, cores: cores ? Number(cores) : null });
|
|
172
|
+
}
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** `ps -A -o pid=,ppid=,comm=` -> Map(pid -> { ppid, name, path }). */
|
|
177
|
+
export function parsePs(text) {
|
|
178
|
+
const map = new Map();
|
|
179
|
+
for (const line of String(text ?? '').split('\n')) {
|
|
180
|
+
const m = /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(line);
|
|
181
|
+
if (!m) continue;
|
|
182
|
+
const path = m[3].replace(/^-/, '');
|
|
183
|
+
map.set(Number(m[1]), { ppid: Number(m[2]), path, name: path.split('/').pop() });
|
|
184
|
+
}
|
|
185
|
+
return map;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Linux /proc/<pid>/stat. The comm field is in parentheses and may contain spaces. */
|
|
189
|
+
export function parseProcStat(text) {
|
|
190
|
+
const str = String(text ?? '');
|
|
191
|
+
const open = str.indexOf('(');
|
|
192
|
+
const close = str.lastIndexOf(')');
|
|
193
|
+
if (open < 0 || close < 0) return null;
|
|
194
|
+
const rest = str.slice(close + 2).split(' ');
|
|
195
|
+
return { name: str.slice(open + 1, close), ppid: Number(rest[1]) };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const ARM_IMPLEMENTERS = {
|
|
199
|
+
'0x41': 'ARM', '0x42': 'Broadcom', '0x43': 'Cavium', '0x48': 'HiSilicon', '0x4e': 'NVIDIA', '0x50': 'APM',
|
|
200
|
+
'0x51': 'Qualcomm', '0x53': 'Samsung', '0x56': 'Marvell', '0x61': 'Apple', '0x69': 'Intel', '0xc0': 'Ampere',
|
|
201
|
+
};
|
|
202
|
+
const ARM_PARTS = {
|
|
203
|
+
'0xd03': 'Cortex-A53', '0xd04': 'Cortex-A35', '0xd05': 'Cortex-A55', '0xd07': 'Cortex-A57', '0xd08': 'Cortex-A72',
|
|
204
|
+
'0xd09': 'Cortex-A73', '0xd0a': 'Cortex-A75', '0xd0b': 'Cortex-A76', '0xd0c': 'Neoverse-N1', '0xd0d': 'Cortex-A77',
|
|
205
|
+
'0xd40': 'Neoverse-V1', '0xd41': 'Cortex-A78', '0xd44': 'Cortex-X1', '0xd46': 'Cortex-A510', '0xd47': 'Cortex-A710',
|
|
206
|
+
'0xd48': 'Cortex-X2', '0xd49': 'Neoverse-N2', '0xd4b': 'Cortex-A78C', '0xd4d': 'Cortex-A715', '0xd4e': 'Cortex-X3',
|
|
207
|
+
'0xd4f': 'Neoverse-V2', '0xd80': 'Cortex-A520', '0xd81': 'Cortex-A720', '0xd82': 'Cortex-X4',
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* CPU name from /proc/cpuinfo when Node's os.cpus() has none (common on ARM, where it
|
|
212
|
+
* reports "unknown"). Note: "processor : 0" is the core index, not a name.
|
|
213
|
+
*/
|
|
214
|
+
export function parseCpuinfoModel(text) {
|
|
215
|
+
const str = String(text ?? '');
|
|
216
|
+
const field = (name) => new RegExp(`^${name}\\s*:\\s*(.+)$`, 'm').exec(str)?.[1]?.trim();
|
|
217
|
+
const named = field('model name') ?? field('Hardware') ?? field('cpu model') ?? field('uarch');
|
|
218
|
+
if (named) return named;
|
|
219
|
+
const impl = field('CPU implementer')?.toLowerCase();
|
|
220
|
+
if (!impl) return null;
|
|
221
|
+
const vendor = ARM_IMPLEMENTERS[impl] ?? `ARM (implementer ${impl})`;
|
|
222
|
+
const part = ARM_PARTS[field('CPU part')?.toLowerCase()];
|
|
223
|
+
return impl === '0x41' && part ? `ARM ${part}` : part ? `${vendor} ${part}` : vendor;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Pull the version out of `<shell> --version` output. */
|
|
227
|
+
export function parseShellVersion(shell, text) {
|
|
228
|
+
const str = String(text ?? '');
|
|
229
|
+
const patterns = {
|
|
230
|
+
bash: /version (\d+\.\d+(?:\.\d+)?)/,
|
|
231
|
+
zsh: /zsh (\d+(?:\.\d+)+)/,
|
|
232
|
+
fish: /version (\d+(?:\.\d+)+)/,
|
|
233
|
+
pwsh: /PowerShell (\d+(?:\.\d+)+)/,
|
|
234
|
+
};
|
|
235
|
+
const m = (patterns[shell] ?? /(\d+(?:\.\d+)+)/).exec(str) ?? /(\d+(?:\.\d+)+)/.exec(str);
|
|
236
|
+
return m ? m[1] : null;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Simple `key = value` / `key value` config files (kitty, ghostty, foot). Last value wins. */
|
|
240
|
+
export function parseConfLines(text, sep = /\s*=\s*|\s+/) {
|
|
241
|
+
const out = {};
|
|
242
|
+
for (const raw of String(text ?? '').split('\n')) {
|
|
243
|
+
const line = raw.trim();
|
|
244
|
+
if (!line || line.startsWith('#') || line.startsWith(';') || line.startsWith('[')) continue;
|
|
245
|
+
const parts = line.split(sep);
|
|
246
|
+
const key = parts.shift();
|
|
247
|
+
if (key) out[key] = parts.join(' ').replace(/^["']|["']$/g, '').trim();
|
|
248
|
+
}
|
|
249
|
+
return out;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** INI sections: { section: { key: value } }. Used for gtk settings.ini and kdeglobals. */
|
|
253
|
+
export function parseIni(text) {
|
|
254
|
+
const out = {};
|
|
255
|
+
let section = '';
|
|
256
|
+
for (const raw of String(text ?? '').split('\n')) {
|
|
257
|
+
const line = raw.trim();
|
|
258
|
+
if (!line || line.startsWith('#') || line.startsWith(';')) continue;
|
|
259
|
+
const sec = /^\[(.+)\]$/.exec(line);
|
|
260
|
+
if (sec) {
|
|
261
|
+
section = sec[1];
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
const kv = /^([^=]+)=(.*)$/.exec(line);
|
|
265
|
+
if (kv) (out[section] ??= {})[kv[1].trim()] = kv[2].trim().replace(/^["']|["']$/g, '');
|
|
266
|
+
}
|
|
267
|
+
return out;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Strip // and /* *\/ comments (and trailing commas) so JSONC config files parse as JSON. */
|
|
271
|
+
export function stripJsonComments(text) {
|
|
272
|
+
let out = '';
|
|
273
|
+
let inString = false;
|
|
274
|
+
for (let i = 0; i < text.length; i++) {
|
|
275
|
+
const ch = text[i];
|
|
276
|
+
const next = text[i + 1];
|
|
277
|
+
if (inString) {
|
|
278
|
+
out += ch;
|
|
279
|
+
if (ch === '\\') out += text[++i] ?? '';
|
|
280
|
+
else if (ch === '"') inString = false;
|
|
281
|
+
} else if (ch === '"') {
|
|
282
|
+
inString = true;
|
|
283
|
+
out += ch;
|
|
284
|
+
} else if (ch === '/' && next === '/') {
|
|
285
|
+
while (i < text.length && text[i] !== '\n') i++;
|
|
286
|
+
out += '\n';
|
|
287
|
+
} else if (ch === '/' && next === '*') {
|
|
288
|
+
i += 2;
|
|
289
|
+
while (i < text.length && !(text[i] === '*' && text[i + 1] === '/')) i++;
|
|
290
|
+
i++;
|
|
291
|
+
} else out += ch;
|
|
292
|
+
}
|
|
293
|
+
return out.replace(/,(\s*[}\]])/g, '$1');
|
|
294
|
+
}
|
package/src/render.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// Layout and coloring.
|
|
2
|
+
//
|
|
3
|
+
// neofetch prints the logo, moves the cursor back up with \e[<n>A, then prefixes every
|
|
4
|
+
// info line with \e[<n>C to jump right of the logo. That breaks when output is piped,
|
|
5
|
+
// captured, or taller than the terminal. peekfetch builds each row as plain text instead:
|
|
6
|
+
// logo line, padded to the logo width, then the gap, then the info line.
|
|
7
|
+
|
|
8
|
+
import { RESET, BOLD, color, padEnd, truncate, visibleWidth } from './ansi.js';
|
|
9
|
+
|
|
10
|
+
const PLACEHOLDER = /\$\{c(\d)\}/g;
|
|
11
|
+
|
|
12
|
+
/** Replace ${cN} placeholders with ANSI colors. Colors carry across lines, like neofetch. */
|
|
13
|
+
export function colorizeLogo(logo, { useColor = true, bold = true } = {}) {
|
|
14
|
+
const plain = logo.art.map((l) => l.replace(PLACEHOLDER, ''));
|
|
15
|
+
const width = Math.max(0, ...plain.map(visibleWidth));
|
|
16
|
+
if (!useColor) return { lines: plain, width };
|
|
17
|
+
|
|
18
|
+
const codes = logo.colors.map((c) => color(c) + (bold ? BOLD : ''));
|
|
19
|
+
let active = codes[0] ?? '';
|
|
20
|
+
const lines = logo.art.map((line) => {
|
|
21
|
+
const start = active;
|
|
22
|
+
const body = line.replace(PLACEHOLDER, (_, n) => {
|
|
23
|
+
active = codes[Number(n) - 1] ?? '';
|
|
24
|
+
return active;
|
|
25
|
+
});
|
|
26
|
+
return `${start}${body}${RESET}`;
|
|
27
|
+
});
|
|
28
|
+
return { lines, width };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Text colors derived from the logo, following neofetch's set_text_colors():
|
|
33
|
+
* title uses the logo's first color, labels its second (or first, if the second is white).
|
|
34
|
+
*/
|
|
35
|
+
export function textPalette(logoColors = [], overrides = null, useColor = true) {
|
|
36
|
+
if (!useColor) return { title: '', at: '', separator: '', label: '', colon: '', info: '' };
|
|
37
|
+
const [c1 = 4, c2 = 7] = logoColors;
|
|
38
|
+
const isFg = (c) => c === 7 || c === '7' || c === 'fg';
|
|
39
|
+
const isGrey = (c) => c === 8 || c === '8';
|
|
40
|
+
// Same order of rules as neofetch, so ties resolve identically.
|
|
41
|
+
let title = color(c1);
|
|
42
|
+
let label = color(c2);
|
|
43
|
+
if (isGrey(c1)) title = RESET;
|
|
44
|
+
if (isGrey(c2)) label = RESET;
|
|
45
|
+
if (isFg(c2)) label = color(c1);
|
|
46
|
+
if (isFg(c1)) title = RESET;
|
|
47
|
+
const palette = { title, at: RESET, separator: RESET, label, colon: RESET, info: RESET };
|
|
48
|
+
for (const [k, v] of Object.entries(overrides ?? {})) if (k in palette) palette[k] = color(v);
|
|
49
|
+
return palette;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Two rows of 8 color swatches: the terminal's 16-color palette. */
|
|
53
|
+
export function colorBlocks() {
|
|
54
|
+
const row = (from) =>
|
|
55
|
+
Array.from({ length: 8 }, (_, i) => {
|
|
56
|
+
const n = from + i;
|
|
57
|
+
return (n < 8 ? `\x1b[4${n}m` : `\x1b[48;5;${n}m`) + ' ';
|
|
58
|
+
}).join('') + RESET;
|
|
59
|
+
return [row(0), row(8)];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Turn detection results into info lines (already colored). */
|
|
63
|
+
export function infoLines(results, { config, palette, useColor }) {
|
|
64
|
+
const bold = useColor && config.bold ? BOLD : '';
|
|
65
|
+
const R = useColor ? RESET : '';
|
|
66
|
+
const out = [];
|
|
67
|
+
const title = results.find((r) => r.key === 'title');
|
|
68
|
+
const titleWidth = title?.entries[0] ? visibleWidth(title.entries[0].text) : 20;
|
|
69
|
+
|
|
70
|
+
for (const r of results) {
|
|
71
|
+
switch (r.key) {
|
|
72
|
+
case 'title': {
|
|
73
|
+
const data = r.data;
|
|
74
|
+
if (!data) break;
|
|
75
|
+
out.push(`${bold}${palette.title}${data.user}${R}${palette.at}@${R}${bold}${palette.title}${data.host}${R}`);
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
case 'separator':
|
|
79
|
+
out.push(`${palette.separator}${config.underline.repeat(titleWidth)}${R}`);
|
|
80
|
+
break;
|
|
81
|
+
case 'break':
|
|
82
|
+
out.push('');
|
|
83
|
+
break;
|
|
84
|
+
case 'colors':
|
|
85
|
+
if (useColor) out.push(...colorBlocks());
|
|
86
|
+
break;
|
|
87
|
+
default:
|
|
88
|
+
for (const { label, text } of r.entries) {
|
|
89
|
+
const name = config.labels?.[r.key] ?? label;
|
|
90
|
+
out.push(`${bold}${palette.label}${name}${R}${palette.colon}${config.separator}${R} ${palette.info}${text}${R}`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
// A trailing blank line (e.g. "break" before a hidden "colors") is noise.
|
|
95
|
+
while (out.length && out.at(-1) === '') out.pop();
|
|
96
|
+
return out;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Put the logo and the info side by side, truncating to the terminal width. */
|
|
100
|
+
export function compose(logo, info, { gap = 3, columns = Infinity } = {}) {
|
|
101
|
+
const left = logo?.lines ?? [];
|
|
102
|
+
const width = logo?.width ?? 0;
|
|
103
|
+
const rows = Math.max(left.length, info.length);
|
|
104
|
+
const out = [];
|
|
105
|
+
for (let i = 0; i < rows; i++) {
|
|
106
|
+
let line;
|
|
107
|
+
if (!left.length) line = info[i] ?? '';
|
|
108
|
+
else if (info[i]) line = padEnd(left[i] ?? '', width) + ' '.repeat(gap) + info[i];
|
|
109
|
+
else line = (left[i] ?? '').replace(/ +$/, '');
|
|
110
|
+
out.push(Number.isFinite(columns) ? truncate(line, columns) : line);
|
|
111
|
+
}
|
|
112
|
+
return out.join('\n') + '\n';
|
|
113
|
+
}
|