Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 | 5x 5x 5x 5x 5x 5x 5x 2x 5x 5x 635x 635x 108x 527x 527x 2012x 2012x 2012x 180x 1832x 1832x 527x 1981x 1981x 410x 410x 410x 1981x 52x 75x 75x 2435x 541x 1894x 71x 1823x 281x 1542x 561x 981x 95x 886x 471x 415x 21x 21x 21x 45x 45x 1981x 1981x 1981x 454x 454x 454x 1827x 1827x 1827x 1827x 7x 7x 1961x 1961x 1955x 12x 12x 3x 12x 12x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x 1x 5x 4x 3x 3x 2x | import * as fs from "fs";
import * as path from "path";
import { execSync, spawn } from "child_process";
import { gzipSync } from "zlib";
import type {
ExistingState,
EnvironmentKey,
DatafileContent,
EntityType,
HistoryEntry,
Commit,
CommitHash,
HistoryEntity,
} from "@featurevisor/types";
import type { CustomParser } from "@featurevisor/parsers";
import { Adapter, DatafileFile, DatafileOptions } from "./adapter";
import { ProjectConfig } from "../config";
import { getCommit } from "../utils/git";
import { CLI_COLOR_CYAN, CLI_COLOR_GREEN, colorize } from "../tester/cliFormat";
export function getExistingStateFilePath(
projectConfig: ProjectConfig,
environment: EnvironmentKey | false,
): string {
const fileName = environment ? `existing-state-${environment}.json` : `existing-state.json`;
return path.join(projectConfig.stateDirectoryPath, fileName);
}
export function getRevisionFilePath(projectConfig: ProjectConfig): string {
return path.join(projectConfig.stateDirectoryPath, projectConfig.revisionFileName);
}
export function getAllEntityFilePathsRecursively(directoryPath, extension?: string) {
let entities: string[] = [];
if (!fs.existsSync(directoryPath)) {
return entities;
}
const files = fs.readdirSync(directoryPath);
for (let i = 0; i < files.length; i++) {
const file = files[i];
const filePath = path.join(directoryPath, file);
if (fs.statSync(filePath).isDirectory()) {
entities = entities.concat(getAllEntityFilePathsRecursively(filePath, extension));
} else Eif (!extension || file.endsWith(`.${extension}`)) {
entities.push(filePath);
}
}
return entities;
}
function isWithinDirectory(directoryPath: string, fileDirectoryPath: string): boolean {
return (
fileDirectoryPath === directoryPath || fileDirectoryPath.startsWith(directoryPath + path.sep)
);
}
function getPathSegmentsFromKey(
namespaceCharacter: string,
key: string,
entityType?: EntityType,
): string[] {
const pathSegments = namespaceCharacter ? key.split(namespaceCharacter) : [key];
if (
entityType === "test" &&
pathSegments.length > 1 &&
["spec", "feature", "segment"].includes(pathSegments[pathSegments.length - 1])
) {
const suffix = pathSegments[pathSegments.length - 1];
pathSegments[pathSegments.length - 2] = `${pathSegments[pathSegments.length - 2]}.${suffix}`;
pathSegments.pop();
}
return pathSegments;
}
export class FilesystemAdapter extends Adapter {
private parser: CustomParser;
constructor(
private config: ProjectConfig,
private rootDirectoryPath?: string,
) {
super();
this.parser = config.parser as CustomParser;
}
getEntityDirectoryPath(entityType: EntityType): string {
if (entityType === "feature") {
return this.config.featuresDirectoryPath;
} else if (entityType === "group") {
return this.config.groupsDirectoryPath;
} else if (entityType === "segment") {
return this.config.segmentsDirectoryPath;
} else if (entityType === "schema") {
return this.config.schemasDirectoryPath;
} else if (entityType === "target") {
return this.config.targetsDirectoryPath;
} else if (entityType === "test") {
return this.config.testsDirectoryPath;
}
return this.config.attributesDirectoryPath;
}
async listSets(): Promise<string[]> {
Iif (!this.config.sets || !fs.existsSync(this.config.setsDirectoryPath)) {
return [];
}
const entries = await fs.promises.readdir(this.config.setsDirectoryPath, {
withFileTypes: true,
});
return entries
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
.sort();
}
getEntityPath(entityType: EntityType, entityKey: string): string {
const basePath = this.getEntityDirectoryPath(entityType);
const pathSegments = getPathSegmentsFromKey(
this.config.namespaceCharacter,
entityKey,
entityType,
);
return path.join(basePath, ...pathSegments) + `.${this.parser.extension}`;
}
async listEntities(entityType: EntityType): Promise<string[]> {
const directoryPath = this.getEntityDirectoryPath(entityType);
const filePaths = getAllEntityFilePathsRecursively(directoryPath, this.parser.extension);
return (
filePaths
// keep only the files with the right extension
.filter((filterPath) => filterPath.endsWith(`.${this.parser.extension}`))
// remove the entity directory path from beginning
.map((filePath) => filePath.replace(directoryPath + path.sep, ""))
// remove the extension from the end
.map((filterPath) => filterPath.replace(`.${this.parser.extension}`, ""))
// take care of windows paths and apply namespace character
.map((filterPath) => filterPath.split(path.sep).join(this.config.namespaceCharacter))
);
}
async entityExists(entityType: EntityType, entityKey: string): Promise<boolean> {
const entityPath = this.getEntityPath(entityType, entityKey);
return fs.existsSync(entityPath);
}
async readEntity<T>(entityType: EntityType, entityKey: string): Promise<T> {
const filePath = this.getEntityPath(entityType, entityKey);
const entityContent = fs.readFileSync(filePath, "utf8");
return this.parser.parse<T>(entityContent, filePath);
}
async writeEntity<T>(entityType: EntityType, entityKey: string, entity: T): Promise<T> {
const filePath = this.getEntityPath(entityType, entityKey);
if (!fs.existsSync(path.dirname(filePath))) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
}
fs.writeFileSync(filePath, this.parser.stringify(entity, filePath));
return entity;
}
async deleteEntity(entityType: EntityType, entityKey: string): Promise<void> {
const filePath = this.getEntityPath(entityType, entityKey);
Iif (!fs.existsSync(filePath)) {
return;
}
fs.unlinkSync(filePath);
}
/**
* State
*/
async readState(environment: EnvironmentKey): Promise<ExistingState> {
const filePath = getExistingStateFilePath(this.config, environment);
Eif (!fs.existsSync(filePath)) {
return {
features: {},
};
}
return require(filePath);
}
async writeState(environment: EnvironmentKey, existingState: ExistingState) {
const filePath = getExistingStateFilePath(this.config, environment);
Eif (!fs.existsSync(this.config.stateDirectoryPath)) {
fs.mkdirSync(this.config.stateDirectoryPath, { recursive: true });
}
fs.writeFileSync(
filePath,
this.config.prettyState
? JSON.stringify(existingState, null, 2)
: JSON.stringify(existingState),
);
}
/**
* Revision
*/
async readRevision(): Promise<string> {
const filePath = getRevisionFilePath(this.config);
if (fs.existsSync(filePath)) {
return fs.readFileSync(filePath, "utf8");
}
return "0";
}
async writeRevision(revision: string): Promise<void> {
const filePath = getRevisionFilePath(this.config);
// write to state directory
if (!fs.existsSync(this.config.stateDirectoryPath)) {
fs.mkdirSync(this.config.stateDirectoryPath, { recursive: true });
}
fs.writeFileSync(filePath, revision);
// write to datafiles directory, as part of the build process
fs.writeFileSync(
path.join(this.config.datafilesDirectoryPath, this.config.revisionFileName),
revision,
);
}
/**
* Datafile
*/
async listDatafiles(): Promise<DatafileFile[]> {
const directoryPath = this.config.datafilesDirectoryPath;
return getAllEntityFilePathsRecursively(directoryPath)
.filter((filePath) => path.basename(filePath) !== this.config.revisionFileName)
.filter((filePath) => !path.basename(filePath).startsWith("."))
.map((filePath) => {
const content = fs.readFileSync(filePath);
return {
path: path.relative(directoryPath, filePath).split(path.sep).join("/"),
size: content.length,
gzipSize: gzipSync(content).length,
};
})
.sort((a, b) => a.path.localeCompare(b.path));
}
getDatafilePath(options: DatafileOptions): string {
const pattern = this.config.datafileNamePattern || "featurevisor-%s.json";
if (!options.target) {
throw new Error("Datafile target is required.");
}
const targetPathSegments = options.target.split(this.config.namespaceCharacter);
const targetFileKey = targetPathSegments.pop() || options.target;
const fileName = pattern.replace("%s", targetFileKey);
const targetDirectory = targetPathSegments.length > 0 ? path.join(...targetPathSegments) : "";
const dir = options.datafilesDir || this.config.datafilesDirectoryPath;
if (options.environment) {
return path.join(dir, options.environment, targetDirectory, fileName);
}
return path.join(dir, targetDirectory, fileName);
}
async readDatafile(options: DatafileOptions): Promise<DatafileContent> {
const filePath = this.getDatafilePath(options);
const content = fs.readFileSync(filePath, "utf8");
const datafileContent = JSON.parse(content);
return datafileContent;
}
async writeDatafile(datafileContent: DatafileContent, options: DatafileOptions): Promise<void> {
const dir = options.datafilesDir || this.config.datafilesDirectoryPath;
const outputFilePath = this.getDatafilePath(options);
fs.mkdirSync(path.dirname(outputFilePath), { recursive: true });
fs.writeFileSync(
outputFilePath,
this.config.prettyDatafile
? JSON.stringify(datafileContent, null, 2)
: JSON.stringify(datafileContent),
);
const root = path.resolve(dir, "..");
const shortPath = outputFilePath.replace(root + path.sep, "");
console.log(` ${colorize("✔", CLI_COLOR_GREEN)} ${colorize(shortPath, CLI_COLOR_CYAN)}`);
}
/**
* History
*/
async getRawHistory(pathPatterns: string[]): Promise<string> {
const gitPaths = pathPatterns.join(" ");
const logCommand = `git log --name-only --pretty=format:"%h|%an|%aI" --relative --no-merges -- ${gitPaths}`;
const fullCommand = `(cd ${this.rootDirectoryPath} && ${logCommand})`;
return new Promise(function (resolve, reject) {
const child = spawn(fullCommand, { shell: true });
let result = "";
child.stdout.on("data", function (data) {
result += data.toString();
});
child.stderr.on("data", function (data) {
console.error(data.toString());
});
child.on("close", function (code) {
if (code === 0) {
resolve(result);
} else {
reject(code);
}
});
});
}
getPathPatterns(entityType?: EntityType, entityKey?: string): string[] {
let pathPatterns: string[] = [];
if (entityType && entityKey) {
pathPatterns = [this.getEntityPath(entityType, entityKey)];
} else if (entityType) {
if (entityType === "attribute") {
pathPatterns = [this.config.attributesDirectoryPath];
} else if (entityType === "segment") {
pathPatterns = [this.config.segmentsDirectoryPath];
} else if (entityType === "feature") {
pathPatterns = [this.config.featuresDirectoryPath];
} else if (entityType === "group") {
pathPatterns = [this.config.groupsDirectoryPath];
} else if (entityType === "schema") {
pathPatterns = [this.config.schemasDirectoryPath];
} else if (entityType === "target") {
pathPatterns = [this.config.targetsDirectoryPath];
} else if (entityType === "test") {
pathPatterns = [this.config.testsDirectoryPath];
}
} else {
pathPatterns = [
this.config.featuresDirectoryPath,
this.config.attributesDirectoryPath,
this.config.segmentsDirectoryPath,
this.config.groupsDirectoryPath,
this.config.schemasDirectoryPath,
this.config.targetsDirectoryPath,
this.config.testsDirectoryPath,
];
}
return pathPatterns.map((p) => p.replace((this.rootDirectoryPath as string) + path.sep, ""));
}
async listHistoryEntries(entityType?: EntityType, entityKey?: string): Promise<HistoryEntry[]> {
const pathPatterns = this.getPathPatterns(entityType, entityKey);
const rawHistory = await this.getRawHistory(pathPatterns);
const fullHistory: HistoryEntry[] = [];
const blocks = rawHistory.split("\n\n");
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i];
if (block.length === 0) {
continue;
}
const lines = block.split("\n");
const commitLine = lines[0];
const [commitHash, author, timestamp] = commitLine.split("|");
const entities: HistoryEntity[] = [];
const filePathLines = lines.slice(1);
for (let j = 0; j < filePathLines.length; j++) {
const relativePath = filePathLines[j];
const absolutePath = path.join(this.rootDirectoryPath as string, relativePath);
const fileName = absolutePath.split(path.sep).pop() as string;
const relativeDir = path.dirname(absolutePath);
const extensionWithDot = "." + this.parser.extension;
const key = fileName.replace(extensionWithDot, "");
let type: EntityType = "attribute";
if (isWithinDirectory(this.config.attributesDirectoryPath, relativeDir)) {
type = "attribute";
} else if (isWithinDirectory(this.config.segmentsDirectoryPath, relativeDir)) {
type = "segment";
} else if (isWithinDirectory(this.config.featuresDirectoryPath, relativeDir)) {
type = "feature";
} else if (isWithinDirectory(this.config.groupsDirectoryPath, relativeDir)) {
type = "group";
} else if (isWithinDirectory(this.config.schemasDirectoryPath, relativeDir)) {
type = "schema";
} else if (isWithinDirectory(this.config.targetsDirectoryPath, relativeDir)) {
type = "target";
} else if (isWithinDirectory(this.config.testsDirectoryPath, relativeDir)) {
type = "test";
} else {
continue;
}
if (type === "feature" || type === "target") {
const entityDirectoryPath =
type === "feature"
? this.config.featuresDirectoryPath
: this.config.targetsDirectoryPath;
const baseRelativePath = absolutePath
.replace(entityDirectoryPath + path.sep, "")
.replace(extensionWithDot, "")
.split(path.sep)
.join(this.config.namespaceCharacter);
entities.push({
type,
key: baseRelativePath,
});
continue;
}
entities.push({
type,
key,
});
}
if (entities.length === 0) {
continue;
}
fullHistory.push({
commit: commitHash,
author,
timestamp,
entities,
});
}
return fullHistory;
}
async readCommit(
commitHash: CommitHash,
entityType?: EntityType,
entityKey?: string,
): Promise<Commit> {
const pathPatterns = this.getPathPatterns(entityType, entityKey);
const gitPaths = pathPatterns.join(" ");
const logCommand = `git show ${commitHash} --relative -- ${gitPaths}`;
const fullCommand = `(cd ${this.rootDirectoryPath} && ${logCommand})`;
const gitShowOutput = execSync(fullCommand, { encoding: "utf8" }).toString();
const commit = getCommit(gitShowOutput, {
rootDirectoryPath: this.rootDirectoryPath as string,
projectConfig: this.config,
});
return commit;
}
}
|