Files
shell-utils/grep-mtime-sorter.mjs

76 lines
1.8 KiB
JavaScript
Executable File
Raw Permalink 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.
#!/usr/bin/env node
/* 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';
import { inspect } from 'node:util';
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 for line ${inspect(line)}`);
}
}
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)/).filter(line => line.trim().length > 0);
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();