feat: add archive reader and tests
- Añade `archiveReader` que lista entradas en ZIP/7z con fallback a `unzip` - Añade tests unitarios que mockean `child_process.exec` para validar parsing - Documenta dependencia de binarios en README y CI (pasos previos)
This commit is contained in:
89
backend/src/services/archiveReader.ts
Normal file
89
backend/src/services/archiveReader.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Servicio: archiveReader
|
||||
*
|
||||
* Lista el contenido de contenedores comunes (ZIP, 7z) sin necesidad de
|
||||
* extraerlos completamente. Intenta usar la utilidad `7z` (7-Zip) con la
|
||||
* opción `-slt` para obtener un listado con metadatos; si falla y el archivo
|
||||
* es ZIP, intenta usar `unzip -l` como fallback.
|
||||
*
|
||||
* La función principal exportada es `listArchiveEntries(filePath, logger)` y
|
||||
* devuelve un array de objetos `{ name, size }` con las entradas encontradas.
|
||||
*
|
||||
* Nota: este servicio depende de binarios del sistema (`7z`, `unzip`) cuando
|
||||
* se trabaja con formatos comprimidos. En entornos de CI/producción debe
|
||||
* asegurarse la presencia de dichas utilidades o los tests deben mockear
|
||||
* las llamadas a `child_process.exec`.
|
||||
*/
|
||||
import path from 'path';
|
||||
import { exec } from 'child_process';
|
||||
|
||||
export type ArchiveEntry = { name: string; size: number };
|
||||
|
||||
export async function listArchiveEntries(
|
||||
filePath: string,
|
||||
logger: { warn?: (...args: any[]) => void } = console
|
||||
): Promise<ArchiveEntry[]> {
|
||||
const ext = path.extname(filePath).toLowerCase().replace(/^\./, '');
|
||||
|
||||
if (!['zip', '7z'].includes(ext)) return [];
|
||||
|
||||
const execCmd = (cmd: string) =>
|
||||
new Promise<{ stdout: string; stderr: string }>((resolve, reject) => {
|
||||
exec(cmd, (err, stdout, stderr) => {
|
||||
if (err) return reject(err);
|
||||
resolve({ stdout: String(stdout), stderr: String(stderr) });
|
||||
});
|
||||
});
|
||||
|
||||
// Intentamos 7z -slt (salida técnica fácil de parsear)
|
||||
const try7z = async () => {
|
||||
const { stdout } = await execCmd(`7z l -slt ${JSON.stringify(filePath)}`);
|
||||
const blocks = String(stdout).split(/\r?\n\r?\n/);
|
||||
const entries: ArchiveEntry[] = [];
|
||||
|
||||
for (const block of blocks) {
|
||||
const lines = block.split(/\r?\n/);
|
||||
const pathLine = lines.find((l) => l.startsWith('Path = '));
|
||||
if (!pathLine) continue;
|
||||
const name = pathLine.replace(/^Path = /, '').trim();
|
||||
const sizeLine = lines.find((l) => l.startsWith('Size = '));
|
||||
const size = sizeLine ? parseInt(sizeLine.replace(/^Size = /, ''), 10) || 0 : 0;
|
||||
entries.push({ name, size });
|
||||
}
|
||||
|
||||
return entries;
|
||||
};
|
||||
|
||||
try {
|
||||
return await try7z();
|
||||
} catch (err) {
|
||||
logger.warn?.({ err, filePath }, 'archiveReader: 7z failed, attempting fallback');
|
||||
|
||||
if (ext === 'zip') {
|
||||
try {
|
||||
const { stdout } = await execCmd(`unzip -l ${JSON.stringify(filePath)}`);
|
||||
const lines = String(stdout).split(/\r?\n/);
|
||||
const entries: ArchiveEntry[] = [];
|
||||
|
||||
for (const line of lines) {
|
||||
// línea típica: " 12345 path/to/file.bin"
|
||||
const m = line.match(/^\s*(\d+)\s+(.+)$/);
|
||||
if (m) {
|
||||
const size = parseInt(m[1], 10);
|
||||
const name = m[2].trim();
|
||||
entries.push({ name, size });
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
} catch (err2) {
|
||||
logger.warn?.({ err2, filePath }, 'archiveReader: unzip fallback failed');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export default { listArchiveEntries };
|
||||
47
backend/tests/services/archiveReader.spec.ts
Normal file
47
backend/tests/services/archiveReader.spec.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
|
||||
// Mockeamos el módulo `child_process` para controlar las llamadas a `exec`.
|
||||
vi.mock('child_process', () => ({ exec: vi.fn() }));
|
||||
import * as child_process from 'child_process';
|
||||
import { listArchiveEntries } from '../../src/services/archiveReader';
|
||||
|
||||
describe('services/archiveReader', () => {
|
||||
it('lista entradas usando 7z -slt', async () => {
|
||||
const stdout = `Path = file1.txt\nSize = 123\nPacked Size = 0\n\nPath = dir/file2.bin\nSize = 456\nPacked Size = 0\n`;
|
||||
|
||||
(child_process as any).exec.mockImplementation((cmd: any, cb: any) => {
|
||||
cb(null, stdout, '');
|
||||
return {} as any;
|
||||
});
|
||||
|
||||
const entries = await listArchiveEntries('/roms/archive.7z', console);
|
||||
expect(entries.length).toBe(2);
|
||||
expect(entries[0].name).toBe('file1.txt');
|
||||
expect(entries[0].size).toBe(123);
|
||||
(child_process as any).exec.mockRestore?.();
|
||||
});
|
||||
|
||||
it('usa unzip como fallback para zip cuando 7z falla', async () => {
|
||||
(child_process as any).exec
|
||||
.mockImplementationOnce((cmd: any, cb: any) => {
|
||||
// simular fallo de 7z
|
||||
cb(new Error('7z not found'), '', '');
|
||||
return {} as any;
|
||||
})
|
||||
.mockImplementationOnce((cmd: any, cb: any) => {
|
||||
// salida simulada de unzip -l
|
||||
cb(null, ' 123 file1.txt\n 456 file2.bin\n', '');
|
||||
return {} as any;
|
||||
});
|
||||
|
||||
const entries = await listArchiveEntries('/roms/archive.zip', console);
|
||||
expect(entries.length).toBe(2);
|
||||
expect(entries[0].name).toBe('file1.txt');
|
||||
(child_process as any).exec.mockRestore?.();
|
||||
});
|
||||
|
||||
it('retorna vacío para formatos no soportados', async () => {
|
||||
const entries = await listArchiveEntries('/roms/simple.bin');
|
||||
expect(entries).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user