Skip to content

Instantly share code, notes, and snippets.

@phucdph
Created October 22, 2024 03:11
Show Gist options
  • Save phucdph/6fdf0f63d6b2ef7f48a9a04b27896858 to your computer and use it in GitHub Desktop.
Save phucdph/6fdf0f63d6b2ef7f48a9a04b27896858 to your computer and use it in GitHub Desktop.
const fs = require("fs");
const path = require("path");
const { minimatch } = require("minimatch");
// Function to parse CODEOWNERS file
function parseCodeowners(codeownersFile) {
const rules = [];
const lines = fs.readFileSync(codeownersFile, "utf-8").split("\n");
lines.forEach((line) => {
line = line.trim();
if (!line || line.startsWith("#")) return; // Ignore comments and empty lines
const parts = line.split(/\s+/);
const pattern = parts[0];
const owners = parts.slice(1);
rules.push({ pattern, owners });
});
return rules;
}
// Function to group files by code owners
function groupFilesByOwners(files, codeownersRules) {
const filesByOwner = {};
files.forEach((file) => {
let matched = false;
// Check each rule in CODEOWNERS
codeownersRules.forEach((rule) => {
const _file = '/' + file;
if (minimatch(_file, rule.pattern) || _file.includes(rule.pattern)) {
matched = true;
rule.owners.forEach((owner) => {
if (!filesByOwner[owner]) {
filesByOwner[owner] = [];
}
filesByOwner[owner].push(file);
});
}
});
// If no owner is found, categorize as 'unowned'
if (!matched) {
if (!filesByOwner["unowned"]) {
filesByOwner["unowned"] = [];
}
filesByOwner["unowned"].push(file);
}
});
return filesByOwner;
}
// Function to read file list from a text file
function readFileList(filePath) {
const fileContent = fs.readFileSync(filePath, "utf-8");
return fileContent
.split("\n")
.map((file) => file.trim())
.filter(Boolean);
}
// Path to the CODEOWNERS file and file list
const codeownersFilePath = path.join(__dirname, "CODEOWNERS");
const fileListPath = path.join(__dirname, "files.txt");
// Parse the CODEOWNERS file and the file list
const codeownersRules = parseCodeowners(codeownersFilePath);
const fileList = readFileList(fileListPath);
// Group the files by owners
const groupedFiles = groupFilesByOwners(fileList, codeownersRules);
// Output the results
console.log("Files grouped by owners:");
Object.entries(groupedFiles)
.sort(([, a], [, b]) => b.length - a.length)
.forEach(([owner, files]) => {
console.log(`Owner: ${owner}`);
files.forEach((file) => {
console.log(` - ${file}`);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment