Files
shell-utils/grep-mtime-sorter.mjs
2026-02-22 03:46:33 +01:00

73 lines
1.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* VIBE ALERT
This code was generated using OpenAIs ChatGPT (GPT-5.2 Thinking, large language model).
The output has not been independently reviewed, audited, or comprehensively validated,
and has only been superficially tested. It should be considered experimental and not fully vetted for production use.
*/
import fs from 'node:fs';
import { stat } from 'node:fs/promises';
const lineRe = /^\x1b\[35m\x1b\[K(.*?)\x1b/;
function isoFormat(timestamp) {
if (timestamp) {
const d = new Date(timestamp * 1000);
const pad = (n) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
} else {
return 'Unknown';
}
}
async function getMtime(line) {
const m = lineRe.exec(line);
if (m) {
const filename = m[1];
try {
const s = await stat(filename);
return s.mtimeMs / 1000;
} catch {
return 0;
}
} else {
throw new Error('Malformed input: ANSI prefix not found');
}
}
async function main() {
const input = await new Promise((resolve) => {
let data = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', (chunk) => { data += chunk; });
process.stdin.on('end', () => { resolve(data); });
});
const lines = input.split(/(?<=\n)/);
const pairs = await Promise.all(
lines.map(async (line, index) => {
const t = await getMtime(line);
return { t, index };
})
);
pairs.sort((a, b) => {
if (a.t !== b.t) {
return a.t - b.t;
} else {
return a.index - b.index;
}
});
for (const { t, index } of pairs) {
const ts = isoFormat(t).padStart(16, ' ');
process.stdout.write(`\x1b[94m${ts}\x1b[0m `);
process.stdout.write(lines[index]);
}
}
await main();