/**
* Diffs two datasets of log files for isolated environments.
*
* @param {string[]} dataset1 - Array of log file paths for the first environment.
* @param {string[]} dataset2 - Array of log file paths for the second environment.
* @param {object} [options] - Optional configuration object.
* @param {string} [options.ignoreCase=true] - Whether to ignore case during comparison.
* @param {string} [options.ignoreWhitespace=true] - Whether to ignore whitespace.
* @returns {Promise<object>} - A promise that resolves to an object containing the diff results.
* The object has the following structure:
* {
* added: string[],
* removed: string[],
* changed: { [logfile: string]: { added: string[], removed: string[] } }
* }
* Returns an error if invalid input is provided.
*/
async function diffLogDatasets(dataset1, dataset2, options = {}) {
const { ignoreCase = true, ignoreWhitespace = true } = options;
if (!Array.isArray(dataset1) || !Array.isArray(dataset2)) {
throw new Error("Datasets must be arrays.");
}
if (dataset1.length === 0 && dataset2.length === 0) {
return { added: [], removed: [], changed: {} };
}
if (dataset1.length === 0) {
return { added: dataset2, removed: [], changed: {} };
}
if (dataset2.length === 0) {
return { added: [], removed: dataset1, changed: {} };
}
const diff = { added: [], removed: [], changed: {} };
// Function to read a log file and return its content
async function readLogFile(filePath) {
try {
const response = await fetch(filePath);
if (!response.ok) {
throw new Error(`Failed to fetch ${filePath}: ${response.status}`);
}
return await response.text();
} catch (error) {
console.error(`Error reading ${filePath}:`, error);
return ""; // Return empty string on error to avoid crashing
}
}
// Read log file contents
const logFiles1 = await Promise.all(dataset1.map(readLogFile));
const logFiles2 = await Promise.all(dataset2.map(readLogFile));
// Find added files
for (const fileContent of logFiles2) {
if (!logFiles1.includes(fileContent)) {
diff.added.push(fileContent);
}
}
// Find removed files
for (const fileContent of logFiles1) {
if (!logFiles2.includes(fileContent)) {
diff.removed.push(fileContent);
}
}
// Find changed files
for (let i = 0; i < Math.min(logFiles1.length, logFiles2.length); i++) {
const file1 = logFiles1[i];
const file2 = logFiles2[i];
if (file1 !== file2) {
diff.changed[dataset1[i]] = {
added: [],
removed: []
};
// Split the files into lines
const lines1 = file1.split('\n');
const lines2 = file2.split('\n');
// Find added lines in file2
for (const line of lines2) {
if (!lines1.includes(line)) {
diff.changed[dataset1[i]].added.push(line);
}
}
// Find removed lines in file1
for (const line of lines1) {
if (!lines2.includes(line)) {
diff.changed[dataset1[i]].removed.push(line);
}
}
}
}
return diff;
}
Add your comment