@factorialco/shadowdog
Version:
<img src="https://raw.githubusercontent.com/factorialco/shadowdog/refs/heads/main/logo.png" alt="drawing" width="100"/>
196 lines (195 loc) • 8.54 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.computeArtifactContentSha = exports.computeFileCacheName = exports.computeCache = exports.processFiles = exports.exit = exports.readShadowdogVersion = exports.chalkFiles = exports.logError = exports.logMessage = void 0;
const crypto = __importStar(require("crypto"));
const glob = __importStar(require("glob"));
const chalk_1 = __importDefault(require("chalk"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const glob_1 = require("glob");
const logMessage = (message) => {
console.log(message);
};
exports.logMessage = logMessage;
const logError = (error) => {
if (process.env.DEBUG) {
console.error(chalk_1.default.red(new Error(error.stack)));
}
};
exports.logError = logError;
const chalkFiles = (files) => files.map((file) => `'${chalk_1.default.blue(file)}'`).join(', ');
exports.chalkFiles = chalkFiles;
const readShadowdogVersion = () => {
const packageJsonPath = path_1.default.resolve(__dirname, '../package.json');
const packageJson = JSON.parse(fs_1.default.readFileSync(packageJsonPath, 'utf-8'));
return packageJson.version;
};
exports.readShadowdogVersion = readShadowdogVersion;
const exit = async (eventEmitter, code) => {
// emit exit event and wait for all listeners to complete
await Promise.all(eventEmitter.listeners('exit').map((listener) => listener()));
eventEmitter.removeAllListeners();
process.exit(code);
};
exports.exit = exit;
// Helper function to check if a file matches an ignore pattern
const matchesIgnorePattern = (filePath, pattern) => {
// Handle exact matches
if (pattern === filePath) {
return true;
}
// Handle directory patterns (e.g., "node_modules" should match "any/path/node_modules" and "any/path/node_modules/anything")
if (pattern.endsWith('/') || !pattern.includes('*')) {
const normalizedPattern = pattern.endsWith('/') ? pattern.slice(0, -1) : pattern;
return filePath === normalizedPattern || filePath.startsWith(normalizedPattern + '/');
}
// Handle glob patterns with ** (e.g., "**/node_modules")
if (pattern.startsWith('**/')) {
const suffix = pattern.slice(3); // Remove "**/" prefix
return filePath.includes(suffix) || filePath.endsWith(suffix);
}
// Handle glob patterns with * (e.g., "*.log")
if (pattern.includes('*')) {
// Convert glob pattern to regex
const regexPattern = pattern
.replace(/\./g, '\\.') // Escape dots
.replace(/\*/g, '.*') // Convert * to .*
.replace(/\*\*/g, '.*'); // Convert ** to .*
const regex = new RegExp(`^${regexPattern}$`);
return regex.test(filePath);
}
return false;
};
const processFiles = (files, ignoredFiles = [], preserveNonExistent = false) => {
// Expand glob patterns and filter to files only
const allFiles = files
.map((file) => path_1.default.join(process.cwd(), file))
.flatMap((globPath) => {
const matches = glob.sync(globPath);
// If preserveNonExistent is true and no matches found, keep the original path
// This is important for dependency tracking when files don't exist yet
if (preserveNonExistent && matches.length === 0 && !globPath.includes('*')) {
return [globPath];
}
return matches;
})
.filter((filePath) => {
// If preserveNonExistent is true, don't filter out non-existent files
// unless they contain glob patterns (which should have been resolved)
if (preserveNonExistent && !path_1.default.relative(process.cwd(), filePath).includes('*')) {
try {
return fs_1.default.statSync(filePath).isFile();
}
catch {
// File doesn't exist, but we want to preserve it for dependency tracking
return true;
}
}
return fs_1.default.statSync(filePath).isFile();
})
.sort();
if (ignoredFiles.length === 0) {
return allFiles.map((filePath) => path_1.default.relative(process.cwd(), filePath));
}
// Convert to relative paths for pattern matching
const relativeFiles = allFiles.map((filePath) => path_1.default.relative(process.cwd(), filePath));
// Filter out ignored files using efficient pattern matching
return relativeFiles.filter((file) => {
return !ignoredFiles.some((pattern) => matchesIgnorePattern(file, pattern));
});
};
exports.processFiles = processFiles;
const computeCache = (files, environment, command) => {
const hash = crypto.createHmac('sha1', '');
files.forEach((filePath) => {
hash.update(filePath);
hash.update(fs_1.default.readFileSync(path_1.default.join(process.cwd(), filePath), 'utf-8'));
});
environment.forEach((env) => { var _a; return hash.update((_a = process.env[env]) !== null && _a !== void 0 ? _a : ''); });
hash.update(command);
hash.update((0, exports.readShadowdogVersion)());
hash.update(process.version);
return hash.digest('hex').slice(0, 10);
};
exports.computeCache = computeCache;
const computeFileCacheName = (currentCache, fileName) => {
const hash = crypto.createHmac('sha1', '');
hash.update(currentCache);
hash.update(fileName);
return hash.digest('hex').slice(0, 10);
};
exports.computeFileCacheName = computeFileCacheName;
// Compute SHA256 hash of artifact content (file or directory)
const computeArtifactContentSha = (artifactPath) => {
try {
const fullPath = path_1.default.join(process.cwd(), artifactPath);
const stats = fs_1.default.statSync(fullPath);
if (stats.isDirectory()) {
// For directories, create a hash based on all file contents and structure
const files = (0, glob_1.sync)('**/*', { cwd: fullPath, nodir: true }).sort();
const hash = crypto.createHash('sha256');
hash.update(`directory:${artifactPath}`);
for (const file of files) {
const filePath = path_1.default.join(fullPath, file);
hash.update(`file:${file}`);
try {
const content = fs_1.default.readFileSync(filePath);
hash.update(content);
}
catch {
// Skip files that can't be read
hash.update('unreadable');
}
}
return hash.digest('hex').slice(0, 10);
}
else {
// For files, hash the content directly
const content = fs_1.default.readFileSync(fullPath);
const hash = crypto.createHash('sha256');
hash.update(content);
return hash.digest('hex').slice(0, 10);
}
}
catch {
// If artifact doesn't exist or can't be read, return null
return null;
}
};
exports.computeArtifactContentSha = computeArtifactContentSha;