peekfetch 0.0.0-stage → 0.1.0
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
package/src/context.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// The detection context: shared, memoized probes that several modules need.
|
|
2
|
+
// neofetch re-runs things like `ps` and `system_profiler` per function; here each runs once.
|
|
3
|
+
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import { readdir, readlink } from 'node:fs/promises';
|
|
6
|
+
import { basename } from 'node:path';
|
|
7
|
+
import { run, readText } from './exec.js';
|
|
8
|
+
import { parseOsRelease, parsePs, parseProcStat, parseSystemProfilerDisplays } from './parsers.js';
|
|
9
|
+
|
|
10
|
+
export function createContext({ config, cache, platform = process.platform, env = process.env }) {
|
|
11
|
+
const memo = new Map();
|
|
12
|
+
const once = (key, fn) => {
|
|
13
|
+
if (!memo.has(key)) memo.set(key, Promise.resolve().then(fn).catch(() => null));
|
|
14
|
+
return memo.get(key);
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const ctx = {
|
|
18
|
+
platform,
|
|
19
|
+
env,
|
|
20
|
+
config,
|
|
21
|
+
cache,
|
|
22
|
+
home: os.homedir(),
|
|
23
|
+
once,
|
|
24
|
+
|
|
25
|
+
osRelease: () =>
|
|
26
|
+
once('os-release', async () => {
|
|
27
|
+
for (const file of ['/etc/os-release', '/usr/lib/os-release', '/etc/lsb-release']) {
|
|
28
|
+
const text = await readText(file);
|
|
29
|
+
if (text) return parseOsRelease(text);
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}),
|
|
33
|
+
|
|
34
|
+
/** Every process as Map(pid -> { ppid, name, path }). Used for WM detection on macOS/BSD. */
|
|
35
|
+
processes: () =>
|
|
36
|
+
once('processes', async () => {
|
|
37
|
+
if (platform === 'linux' || platform === 'android') {
|
|
38
|
+
const map = new Map();
|
|
39
|
+
const pids = (await readdir('/proc').catch(() => [])).filter((p) => /^\d+$/.test(p));
|
|
40
|
+
await Promise.all(
|
|
41
|
+
pids.map(async (pid) => {
|
|
42
|
+
const info = parseProcStat(await readText(`/proc/${pid}/stat`));
|
|
43
|
+
if (info) map.set(Number(pid), { ...info, path: info.name });
|
|
44
|
+
}),
|
|
45
|
+
);
|
|
46
|
+
return map;
|
|
47
|
+
}
|
|
48
|
+
if (platform === 'win32') {
|
|
49
|
+
const cim = await ctx.windowsInfo();
|
|
50
|
+
const map = new Map();
|
|
51
|
+
for (const [pid, [ppid, name]] of Object.entries(cim?.proc ?? {})) {
|
|
52
|
+
map.set(Number(pid), { ppid: Number(ppid), name: String(name).replace(/\.exe$/i, ''), path: name });
|
|
53
|
+
}
|
|
54
|
+
return map;
|
|
55
|
+
}
|
|
56
|
+
return parsePs(await run('ps', ['-A', '-o', 'pid=,ppid=,comm=']));
|
|
57
|
+
}),
|
|
58
|
+
|
|
59
|
+
/** Our ancestor processes, nearest first. Used to find the shell and the terminal. */
|
|
60
|
+
ancestors: () =>
|
|
61
|
+
once('ancestors', async () => {
|
|
62
|
+
const chain = [];
|
|
63
|
+
let pid = process.ppid;
|
|
64
|
+
if (platform === 'linux' || platform === 'android') {
|
|
65
|
+
// pid 1 is included: in a container it is often the shell itself.
|
|
66
|
+
for (let depth = 0; pid >= 1 && depth < 32; depth++) {
|
|
67
|
+
const stat = parseProcStat(await readText(`/proc/${pid}/stat`));
|
|
68
|
+
if (!stat) break;
|
|
69
|
+
const exe = await readlink(`/proc/${pid}/exe`).catch(() => null);
|
|
70
|
+
// comm is truncated to 15 chars; the exe name fixes that, but not for
|
|
71
|
+
// multi-call binaries (busybox), where comm is the applet name we want.
|
|
72
|
+
const exeName = exe ? basename(exe) : null;
|
|
73
|
+
const name = stat.name.length >= 15 && exeName?.startsWith(stat.name) ? exeName : stat.name;
|
|
74
|
+
chain.push({ pid, name, path: exe });
|
|
75
|
+
if (pid === 1) break;
|
|
76
|
+
pid = stat.ppid;
|
|
77
|
+
}
|
|
78
|
+
return chain;
|
|
79
|
+
}
|
|
80
|
+
const procs = await ctx.processes();
|
|
81
|
+
for (let depth = 0; procs && pid > 1 && depth < 32; depth++) {
|
|
82
|
+
const p = procs.get(pid);
|
|
83
|
+
if (!p) break;
|
|
84
|
+
chain.push({ pid, name: p.name, path: p.path });
|
|
85
|
+
pid = p.ppid;
|
|
86
|
+
}
|
|
87
|
+
return chain;
|
|
88
|
+
}),
|
|
89
|
+
|
|
90
|
+
/** macOS display + GPU info. system_profiler is the slowest probe (~300 ms), so it is shared. */
|
|
91
|
+
darwinDisplays: () =>
|
|
92
|
+
once('darwin-displays', async () => parseSystemProfilerDisplays(await run('system_profiler', ['SPDisplaysDataType', '-json'], { timeout: 5000 }))),
|
|
93
|
+
|
|
94
|
+
/** Windows: one PowerShell call that gathers everything we need from CIM. */
|
|
95
|
+
windowsInfo: () =>
|
|
96
|
+
once('windows-cim', async () => {
|
|
97
|
+
const script = [
|
|
98
|
+
"$ErrorActionPreference='SilentlyContinue'",
|
|
99
|
+
'$o=@{}',
|
|
100
|
+
'$o.cs=Get-CimInstance Win32_ComputerSystem|Select-Object Manufacturer,Model',
|
|
101
|
+
'$o.os=Get-CimInstance Win32_OperatingSystem|Select-Object Caption,Version,OSArchitecture',
|
|
102
|
+
'$o.gpu=@(Get-CimInstance Win32_VideoController|Select-Object Name,CurrentHorizontalResolution,CurrentVerticalResolution,CurrentRefreshRate)',
|
|
103
|
+
'$o.bat=@(Get-CimInstance Win32_Battery|Select-Object EstimatedChargeRemaining,BatteryStatus)',
|
|
104
|
+
'$p=@{};Get-CimInstance Win32_Process|ForEach-Object{$p[[string]$_.ProcessId]=@($_.ParentProcessId,$_.Name)}',
|
|
105
|
+
'$o.proc=$p',
|
|
106
|
+
'$o|ConvertTo-Json -Depth 4 -Compress',
|
|
107
|
+
].join(';');
|
|
108
|
+
const out = await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { timeout: 8000, env: process.env });
|
|
109
|
+
return out ? JSON.parse(out) : null;
|
|
110
|
+
}),
|
|
111
|
+
};
|
|
112
|
+
return ctx;
|
|
113
|
+
}
|
package/src/exec.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Small, failure-tolerant wrappers around child processes and the filesystem.
|
|
2
|
+
// Every probe in peekfetch may fail (missing tool, sandbox, odd OS); failures resolve to null.
|
|
3
|
+
|
|
4
|
+
import { execFile } from 'node:child_process';
|
|
5
|
+
import { access, readFile, readdir, constants } from 'node:fs/promises';
|
|
6
|
+
import { delimiter, join } from 'node:path';
|
|
7
|
+
|
|
8
|
+
const C_LOCALE = { ...process.env, LC_ALL: 'C', LANG: 'C' };
|
|
9
|
+
|
|
10
|
+
/** Run a command, resolve to stdout (string) or null. Never throws. */
|
|
11
|
+
export function run(cmd, args = [], { timeout = 2000, env = C_LOCALE, input } = {}) {
|
|
12
|
+
return new Promise((resolve) => {
|
|
13
|
+
let child;
|
|
14
|
+
try {
|
|
15
|
+
child = execFile(
|
|
16
|
+
cmd,
|
|
17
|
+
args,
|
|
18
|
+
{ timeout, env, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, windowsHide: true },
|
|
19
|
+
(err, stdout) => {
|
|
20
|
+
// Some tools exit non-zero yet print what we need; keep stdout when there is any.
|
|
21
|
+
if (err && !stdout) resolve(null);
|
|
22
|
+
else resolve(stdout);
|
|
23
|
+
},
|
|
24
|
+
);
|
|
25
|
+
} catch {
|
|
26
|
+
resolve(null);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
if (input !== undefined) child.stdin?.end(input);
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const whichCache = new Map();
|
|
34
|
+
|
|
35
|
+
/** Resolve an executable on PATH without spawning `which`. */
|
|
36
|
+
export function which(name) {
|
|
37
|
+
if (whichCache.has(name)) return whichCache.get(name);
|
|
38
|
+
const promise = (async () => {
|
|
39
|
+
const dirs = (process.env.PATH ?? '').split(delimiter).filter(Boolean);
|
|
40
|
+
const exts = process.platform === 'win32' ? (process.env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';') : [''];
|
|
41
|
+
for (const dir of dirs) {
|
|
42
|
+
for (const ext of exts) {
|
|
43
|
+
const candidate = join(dir, name + ext);
|
|
44
|
+
try {
|
|
45
|
+
await access(candidate, process.platform === 'win32' ? constants.F_OK : constants.X_OK);
|
|
46
|
+
return candidate;
|
|
47
|
+
} catch {
|
|
48
|
+
// keep looking
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return null;
|
|
53
|
+
})();
|
|
54
|
+
whichCache.set(name, promise);
|
|
55
|
+
return promise;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function readText(path) {
|
|
59
|
+
try {
|
|
60
|
+
return await readFile(path, 'utf8');
|
|
61
|
+
} catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Count directory entries (optionally only those passing `filter`). null if the dir is missing. */
|
|
67
|
+
export async function countDir(path, filter = (name) => !name.startsWith('.')) {
|
|
68
|
+
try {
|
|
69
|
+
const entries = await readdir(path);
|
|
70
|
+
return entries.filter(filter).length;
|
|
71
|
+
} catch {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function exists(path) {
|
|
77
|
+
try {
|
|
78
|
+
await access(path);
|
|
79
|
+
return true;
|
|
80
|
+
} catch {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Race a promise against a timer; resolves to `fallback` on timeout. */
|
|
86
|
+
export function withTimeout(promise, ms, fallback = null) {
|
|
87
|
+
let timer;
|
|
88
|
+
const timeout = new Promise((resolve) => {
|
|
89
|
+
timer = setTimeout(() => resolve(fallback), ms);
|
|
90
|
+
timer.unref?.();
|
|
91
|
+
});
|
|
92
|
+
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
|
|
93
|
+
}
|
package/src/format.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// Pure formatting helpers. No I/O here, so everything is unit-testable.
|
|
2
|
+
|
|
3
|
+
import { RESET, DIM } from './ansi.js';
|
|
4
|
+
|
|
5
|
+
/** "3 days, 8 hours, 21 mins". Same rules as neofetch: singulars, zero fields hidden. */
|
|
6
|
+
export function formatUptime(totalSeconds) {
|
|
7
|
+
const s = Math.max(0, Math.floor(totalSeconds));
|
|
8
|
+
const parts = [
|
|
9
|
+
[Math.floor(s / 86400), 'day'],
|
|
10
|
+
[Math.floor((s / 3600) % 24), 'hour'],
|
|
11
|
+
[Math.floor((s / 60) % 60), 'min'],
|
|
12
|
+
]
|
|
13
|
+
.filter(([n]) => n > 0)
|
|
14
|
+
.map(([n, unit]) => `${n} ${unit}${n === 1 ? '' : 's'}`);
|
|
15
|
+
return parts.length ? parts.join(', ') : `${s} secs`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const UNITS = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
|
|
19
|
+
|
|
20
|
+
/** 1024-based, two decimals: "20.04 GiB". */
|
|
21
|
+
export function formatBytes(bytes) {
|
|
22
|
+
if (!Number.isFinite(bytes) || bytes < 0) return '?';
|
|
23
|
+
let i = 0;
|
|
24
|
+
let v = bytes;
|
|
25
|
+
while (v >= 1024 && i < UNITS.length - 1) {
|
|
26
|
+
v /= 1024;
|
|
27
|
+
i++;
|
|
28
|
+
}
|
|
29
|
+
return `${i === 0 ? v : v.toFixed(2)} ${UNITS[i]}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const percent = (used, total) => (total > 0 ? Math.round((used / total) * 100) : 0);
|
|
33
|
+
|
|
34
|
+
/** Green below 50 %, yellow below 80 %, red above. */
|
|
35
|
+
export function levelColor(pct) {
|
|
36
|
+
if (pct < 50) return '\x1b[32m';
|
|
37
|
+
if (pct < 80) return '\x1b[33m';
|
|
38
|
+
return '\x1b[31m';
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Color `text` by a 0-100 usage level (higher = worse). */
|
|
42
|
+
export function colorByLevel(text, level, useColor) {
|
|
43
|
+
return useColor ? `${levelColor(level)}${text}${RESET}` : text;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export const colorPercent = (pct, useColor) => colorByLevel(`${pct}%`, pct, useColor);
|
|
47
|
+
|
|
48
|
+
/** "used / total (pct%)" with an optional usage bar. */
|
|
49
|
+
export function formatUsage(used, total, { useColor = false, bars = false, barWidth = 12 } = {}) {
|
|
50
|
+
const pct = percent(used, total);
|
|
51
|
+
const text = `${formatBytes(used)} / ${formatBytes(total)} (${colorPercent(pct, useColor)})`;
|
|
52
|
+
return bars ? `${bar(pct, barWidth, useColor)} ${text}` : text;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function bar(pct, width = 12, useColor = false) {
|
|
56
|
+
const filled = Math.round((Math.min(100, Math.max(0, pct)) / 100) * width);
|
|
57
|
+
const on = '█'.repeat(filled);
|
|
58
|
+
const off = '░'.repeat(width - filled);
|
|
59
|
+
return useColor ? `${levelColor(pct)}${on}${RESET}${DIM}${off}${RESET}` : `[${'#'.repeat(filled)}${'-'.repeat(width - filled)}]`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Strip marketing noise from CPU names, like neofetch's cpu cleanup. */
|
|
63
|
+
export function cleanCpuName(name) {
|
|
64
|
+
return String(name)
|
|
65
|
+
.replace(/\((R|TM|tm|r)\)|®|™/g, '')
|
|
66
|
+
.replace(/\bCPU\b/g, '')
|
|
67
|
+
.replace(/\s+@\s*[\d.]+\s*[GM]Hz/i, '')
|
|
68
|
+
.replace(/\b(Processor|processor)\b/g, '')
|
|
69
|
+
.replace(/\b(Dual|Quad|Six|Eight|Twelve|Sixteen|\d+)-Core\b/gi, '')
|
|
70
|
+
.replace(/\bwith Radeon.*$/i, '')
|
|
71
|
+
.replace(/\s+/g, ' ')
|
|
72
|
+
.trim();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** "NVIDIA Corporation GA104 [GeForce RTX 3070]" -> "NVIDIA GeForce RTX 3070". */
|
|
76
|
+
export function cleanGpuName(vendor, device) {
|
|
77
|
+
const v = String(vendor ?? '')
|
|
78
|
+
.replace(/Advanced Micro Devices, Inc\.\s*\[AMD\/ATI\]|Advanced Micro Devices.*|AMD\/ATI/i, 'AMD')
|
|
79
|
+
.replace(/NVIDIA Corporation/i, 'NVIDIA')
|
|
80
|
+
.replace(/Intel Corporation/i, 'Intel')
|
|
81
|
+
.replace(/\s*(Corporation|Inc\.|Co\., Ltd\.?)\s*/g, ' ')
|
|
82
|
+
.trim();
|
|
83
|
+
let d = String(device ?? '').trim();
|
|
84
|
+
const bracket = /\[([^\]]+)\]/.exec(d);
|
|
85
|
+
if (bracket) d = bracket[1];
|
|
86
|
+
d = d.replace(/\(rev [0-9a-f]+\)/i, '').trim();
|
|
87
|
+
if (!v) return d;
|
|
88
|
+
if (d.toLowerCase().startsWith(v.toLowerCase())) return d;
|
|
89
|
+
return `${v} ${d}`.trim();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function formatMHz(mhz) {
|
|
93
|
+
if (!mhz || mhz <= 0) return '';
|
|
94
|
+
return mhz >= 1000 ? `${(mhz / 1000).toFixed(2)} GHz` : `${mhz} MHz`;
|
|
95
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
import { parseArgs, HELP } from './cli.js';
|
|
4
|
+
import { loadConfig, configPath, defaultConfigText } from './config.js';
|
|
5
|
+
import { createCache } from './cache.js';
|
|
6
|
+
import { createContext } from './context.js';
|
|
7
|
+
import { withTimeout } from './exec.js';
|
|
8
|
+
import { MODULES, LAYOUT_MODULES, ALL_MODULE_KEYS, normalizeResult } from './modules/index.js';
|
|
9
|
+
import { distro } from './modules/system.js';
|
|
10
|
+
import { findLogo, listLogos, logoFromText } from './logos/index.js';
|
|
11
|
+
import { colorizeLogo, textPalette, infoLines, compose } from './render.js';
|
|
12
|
+
|
|
13
|
+
const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
14
|
+
|
|
15
|
+
function shouldColor(args, env, stream) {
|
|
16
|
+
if (args.noColor) return false;
|
|
17
|
+
if (args.forceColor || (env.FORCE_COLOR && env.FORCE_COLOR !== '0')) return true;
|
|
18
|
+
if ('NO_COLOR' in env && env.NO_COLOR !== '') return false;
|
|
19
|
+
return Boolean(stream.isTTY) && env.TERM !== 'dumb';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Run every module concurrently; each gets `timeout` ms before it is dropped. */
|
|
23
|
+
async function detect(keys, ctx, timeout) {
|
|
24
|
+
return Promise.all(
|
|
25
|
+
keys.map(async (key) => {
|
|
26
|
+
if (LAYOUT_MODULES.has(key)) return { key, entries: [], data: null, ms: 0 };
|
|
27
|
+
const mod = MODULES.get(key);
|
|
28
|
+
const t0 = performance.now();
|
|
29
|
+
let raw = null;
|
|
30
|
+
let error = null;
|
|
31
|
+
try {
|
|
32
|
+
raw = await withTimeout(Promise.resolve().then(() => mod.get(ctx)), timeout, null);
|
|
33
|
+
} catch (err) {
|
|
34
|
+
error = err;
|
|
35
|
+
}
|
|
36
|
+
return { key, ...normalizeResult(mod, raw), ms: performance.now() - t0, error };
|
|
37
|
+
}),
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function pickLogo(config, ctx) {
|
|
42
|
+
if (config.logo === 'none') return null;
|
|
43
|
+
if (config.logo && config.logo !== 'auto') {
|
|
44
|
+
// Only path-like values are files, so `--logo arch` never picks up a stray ./arch file.
|
|
45
|
+
if (/[\\/.]/.test(config.logo) && existsSync(config.logo)) return logoFromText(readFileSync(config.logo, 'utf8'), config.logoColors ?? undefined);
|
|
46
|
+
return findLogo([config.logo], { small: config.smallLogo });
|
|
47
|
+
}
|
|
48
|
+
const d = await distro(ctx);
|
|
49
|
+
return findLogo(d?.logoNames ?? ['Linux'], { small: config.smallLogo });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function main(argv, { stdout = process.stdout, stderr = process.stderr, env = process.env } = {}) {
|
|
53
|
+
let args;
|
|
54
|
+
try {
|
|
55
|
+
args = parseArgs(argv);
|
|
56
|
+
} catch (err) {
|
|
57
|
+
stderr.write(`peekfetch: ${err.message}\nTry 'peekfetch --help'.\n`);
|
|
58
|
+
return 2;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (args.help) return stdout.write(HELP), 0;
|
|
62
|
+
if (args.version) return stdout.write(`peekfetch ${VERSION}\n`), 0;
|
|
63
|
+
if (args.listLogos) return stdout.write(listLogos().join('\n') + '\n'), 0;
|
|
64
|
+
if (args.listModules) return stdout.write(ALL_MODULE_KEYS.join('\n') + '\n'), 0;
|
|
65
|
+
if (args.printConfig) return stdout.write(defaultConfigText()), 0;
|
|
66
|
+
|
|
67
|
+
const path = args.config ?? configPath(env);
|
|
68
|
+
if (args.genConfig) {
|
|
69
|
+
if (existsSync(path) && !args.force) {
|
|
70
|
+
stderr.write(`peekfetch: ${path} already exists (use --force to overwrite)\n`);
|
|
71
|
+
return 1;
|
|
72
|
+
}
|
|
73
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
74
|
+
writeFileSync(path, defaultConfigText());
|
|
75
|
+
stdout.write(`wrote ${path}\n`);
|
|
76
|
+
return 0;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
let config;
|
|
80
|
+
try {
|
|
81
|
+
config = loadConfig(path, { required: Boolean(args.config) });
|
|
82
|
+
} catch (err) {
|
|
83
|
+
stderr.write(`peekfetch: ${err.message}\n`);
|
|
84
|
+
return 1;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// CLI flags win over the config file.
|
|
88
|
+
if (args.modules) config.modules = args.modules;
|
|
89
|
+
if (args.logo) config.logo = args.logo;
|
|
90
|
+
if (args.noLogo || args.stdout) config.logo = 'none';
|
|
91
|
+
if (args.small) config.smallLogo = true;
|
|
92
|
+
if (args.bars) config.bars = true;
|
|
93
|
+
if (args.logoColors) config.logoColors = args.logoColors;
|
|
94
|
+
|
|
95
|
+
const unknown = config.modules.filter((k) => !MODULES.has(k) && !LAYOUT_MODULES.has(k));
|
|
96
|
+
if (unknown.length) {
|
|
97
|
+
stderr.write(`peekfetch: unknown module(s): ${unknown.join(', ')} (see --list-modules)\n`);
|
|
98
|
+
return 2;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const useColor = !args.json && !args.stdout && shouldColor(args, env, stdout);
|
|
102
|
+
const cache = createCache({ enabled: !args.noCache });
|
|
103
|
+
const ctx = createContext({ config: { ...config, useColor }, cache, env });
|
|
104
|
+
|
|
105
|
+
const keys = args.json ? config.modules.filter((k) => !LAYOUT_MODULES.has(k)) : config.modules;
|
|
106
|
+
const [results, logo] = await Promise.all([detect(keys, ctx, config.timeout), pickLogo(config, ctx)]);
|
|
107
|
+
cache.flush();
|
|
108
|
+
|
|
109
|
+
if (args.json) {
|
|
110
|
+
const out = Object.fromEntries(results.map((r) => [r.key, r.data ?? null]));
|
|
111
|
+
stdout.write(JSON.stringify(out, null, 2) + '\n');
|
|
112
|
+
} else {
|
|
113
|
+
const columns = stdout.isTTY && stdout.columns ? stdout.columns : Infinity;
|
|
114
|
+
// Text colors come from the distro logo even when the logo itself is hidden.
|
|
115
|
+
const colorSource = logo ?? (useColor ? await pickLogo({ ...config, logo: 'auto' }, ctx) : null);
|
|
116
|
+
const colors = config.logoColors ?? colorSource?.colors ?? [];
|
|
117
|
+
let art =logo ? colorizeLogo(config.logoColors ? { ...logo, colors } : logo, { useColor, bold: config.bold }) : null;
|
|
118
|
+
|
|
119
|
+
// Narrow terminal: try the small logo, then drop the logo rather than wrapping lines.
|
|
120
|
+
const MIN_INFO = 30;
|
|
121
|
+
if (art && art.width + config.gap + MIN_INFO > columns) {
|
|
122
|
+
const small = config.smallLogo ? null : await pickLogo({ ...config, smallLogo: true }, ctx);
|
|
123
|
+
const smallArt = small && /_small$/i.test(small.name) ? colorizeLogo(small, { useColor, bold: config.bold }) : null;
|
|
124
|
+
art = smallArt && smallArt.width + config.gap + MIN_INFO <= columns ? smallArt : null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const palette = textPalette(colors, config.textColors, useColor);
|
|
128
|
+
const lines = infoLines(results, { config, palette, useColor });
|
|
129
|
+
stdout.write(compose(art, lines, { gap: config.gap, columns }));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (args.timing) {
|
|
133
|
+
const rows = [...results].filter((r) => r.ms > 0).sort((a, b) => b.ms - a.ms);
|
|
134
|
+
stderr.write(rows.map((r) => `${r.key.padEnd(12)} ${r.ms.toFixed(1).padStart(7)} ms${r.error ? ` (error: ${r.error.message})` : ''}`).join('\n') + '\n');
|
|
135
|
+
}
|
|
136
|
+
return 0;
|
|
137
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Logo lookup. The data is extracted from neofetch (MIT) by scripts/extract-neofetch-logos.mjs.
|
|
2
|
+
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
|
|
5
|
+
let logos = null;
|
|
6
|
+
|
|
7
|
+
function load() {
|
|
8
|
+
if (!logos) {
|
|
9
|
+
const raw = JSON.parse(readFileSync(new URL('./logos.json', import.meta.url), 'utf8'));
|
|
10
|
+
logos = raw.map((l) => ({ ...l, regexes: l.patterns.map((p) => new RegExp(p, 'i')) }));
|
|
11
|
+
}
|
|
12
|
+
return logos;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const matchOne = (name) => load().find((l) => l.regexes.some((r) => r.test(name.trim())));
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Find the first logo matching any of `names` (in priority order), like neofetch's
|
|
19
|
+
* `case $ascii_distro in` with nocasematch. With `small`, `<name>_small` variants win.
|
|
20
|
+
*/
|
|
21
|
+
export function findLogo(names, { small = false } = {}) {
|
|
22
|
+
const candidates = names.filter(Boolean).map(String);
|
|
23
|
+
if (small) {
|
|
24
|
+
for (const n of candidates) {
|
|
25
|
+
const hit = matchOne(`${n.replace(/\s+/g, '')}_small`);
|
|
26
|
+
if (hit && /_small$/i.test(hit.name)) return hit;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
for (const n of candidates) {
|
|
30
|
+
const hit = matchOne(n);
|
|
31
|
+
if (hit) return hit;
|
|
32
|
+
}
|
|
33
|
+
return matchOne('Linux');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function listLogos() {
|
|
37
|
+
return [...new Set(load().map((l) => l.name))].sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A logo from a user's text file. ${c1}..${c6} placeholders work as in neofetch. */
|
|
41
|
+
export function logoFromText(text, colors = [6, 4, 2, 3, 5, 1]) {
|
|
42
|
+
const art = text.replace(/\r/g, '').replace(/\n+$/, '').split('\n');
|
|
43
|
+
return { name: 'custom', colors, art };
|
|
44
|
+
}
|