All files / src/find-usage index.ts

0% Statements 0/226
0% Branches 0/106
0% Functions 0/42
0% Lines 0/216

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 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import type { Condition, FeatureKey, SegmentKey, AttributeKey } from "@featurevisor/types";
 
import { Dependencies } from "../dependencies";
import { Plugin } from "../cli";
import {
  extractAttributeKeysFromConditions,
  extractSegmentKeysFromGroupSegments,
} from "../utils/extractKeys";
import { getProjectSetExecutions, printSetHeader } from "../sets";
import {
  CLI_COLOR_CYAN,
  CLI_COLOR_DIM,
  CLI_FORMAT_BOLD,
  CLI_FORMAT_GREEN,
  CLI_FORMAT_YELLOW,
  colorize,
} from "../tester/cliFormat";
 
export interface UsageInFeatures {
  [featureKey: string]: {
    features: Set<FeatureKey>;
    segments: Set<SegmentKey>;
    attributes: Set<AttributeKey>;
  };
}
 
export async function findAllUsageInFeatures(deps: Dependencies): Promise<UsageInFeatures> {
  const { datasource, projectConfig } = deps;
  const usageInFeatures: UsageInFeatures = {};
 
  const featureKeys = await datasource.listFeatures();
 
  for (const featureKey of featureKeys) {
    const feature = await datasource.readFeature(featureKey);
    usageInFeatures[featureKey] = {
      features: new Set<FeatureKey>(),
      segments: new Set<SegmentKey>(),
      attributes: new Set<AttributeKey>(),
    };
 
    // required
    if (feature.required) {
      feature.required.forEach((required) => {
        if (typeof required === "string") {
          usageInFeatures[featureKey].features.add(required);
        } else if (typeof required === "object" && required.key) {
          usageInFeatures[featureKey].features.add(required.key);
        }
      });
    }
 
    // bucketBy
    if (feature.bucketBy) {
      if (typeof feature.bucketBy === "string") {
        usageInFeatures[featureKey].attributes.add(feature.bucketBy);
      } else if (Array.isArray(feature.bucketBy)) {
        feature.bucketBy.forEach((b) => usageInFeatures[featureKey].attributes.add(b));
      } else if (typeof feature.bucketBy === "object" && feature.bucketBy.or) {
        feature.bucketBy.or.forEach((b) => usageInFeatures[featureKey].attributes.add(b));
      }
    }
 
    // variable overrides inside variations
    if (feature.variations) {
      feature.variations.forEach((variation) => {
        if (variation.variableOverrides) {
          Object.keys(variation.variableOverrides).forEach((variableKey) => {
            const overrides = variation.variableOverrides?.[variableKey];
 
            if (overrides) {
              overrides.forEach((override) => {
                if (override.segments) {
                  extractSegmentKeysFromGroupSegments(override.segments).forEach((segmentKey) =>
                    usageInFeatures[featureKey].segments.add(segmentKey),
                  );
                }
 
                if (override.conditions) {
                  extractAttributeKeysFromConditions(override.conditions).forEach((attributeKey) =>
                    usageInFeatures[featureKey].attributes.add(attributeKey),
                  );
                }
              });
            }
          });
        }
      });
    }
 
    // with environments
    if (Array.isArray(projectConfig.environments)) {
      projectConfig.environments.forEach((environment) => {
        // force
        if (feature.force && feature.force[environment]) {
          feature.force[environment].forEach((force) => {
            if (force.segments) {
              extractSegmentKeysFromGroupSegments(force.segments).forEach((segmentKey) =>
                usageInFeatures[featureKey].segments.add(segmentKey),
              );
            }
 
            if (force.conditions) {
              extractAttributeKeysFromConditions(force.conditions).forEach((attributeKey) =>
                usageInFeatures[featureKey].attributes.add(attributeKey),
              );
            }
          });
        }
 
        // rules
        if (feature.rules && feature.rules[environment]) {
          feature.rules[environment].forEach((rule) => {
            extractSegmentKeysFromGroupSegments(rule.segments).forEach((segmentKey) =>
              usageInFeatures[featureKey].segments.add(segmentKey),
            );
          });
        }
      });
    }
 
    // no environments
    if (!Array.isArray(projectConfig.environments)) {
      // force
      if (Array.isArray(feature.force)) {
        feature.force.forEach((force) => {
          if (force.segments) {
            extractSegmentKeysFromGroupSegments(force.segments).forEach((segmentKey) =>
              usageInFeatures[featureKey].segments.add(segmentKey),
            );
          }
 
          if (force.conditions) {
            extractAttributeKeysFromConditions(force.conditions).forEach((attributeKey) =>
              usageInFeatures[featureKey].attributes.add(attributeKey),
            );
          }
        });
      }
 
      // rules
      if (Array.isArray(feature.rules)) {
        feature.rules.forEach((rule) => {
          extractSegmentKeysFromGroupSegments(rule.segments).forEach((segmentKey) =>
            usageInFeatures[featureKey].segments.add(segmentKey),
          );
        });
      }
    }
  }
 
  return usageInFeatures;
}
 
export interface UsageInSegments {
  [segmentKey: string]: {
    attributes: Set<AttributeKey>;
  };
}
 
export async function findAllUsageInSegments(deps: Dependencies): Promise<UsageInSegments> {
  const { datasource } = deps;
  const usageInSegments: UsageInSegments = {};
 
  const segmentKeys = await datasource.listSegments();
 
  for (const segmentKey of segmentKeys) {
    const segment = await datasource.readSegment(segmentKey);
    usageInSegments[segmentKey] = {
      attributes: new Set<AttributeKey>(),
    };
 
    extractAttributeKeysFromConditions(segment.conditions as Condition | Condition[]).forEach(
      (attributeKey) => {
        usageInSegments[segmentKey].attributes.add(attributeKey);
      },
    );
  }
 
  return usageInSegments;
}
 
export async function findFeatureUsage(
  usageInFeatures: UsageInFeatures,
  searchFeatureKey: FeatureKey,
): Promise<Set<FeatureKey>> {
  const usedInFeatures = new Set<FeatureKey>();
 
  for (const featureKey in usageInFeatures) {
    if (usageInFeatures[featureKey].features.has(searchFeatureKey)) {
      usedInFeatures.add(featureKey);
    }
  }
 
  return usedInFeatures;
}
 
export async function findSegmentUsage(
  usageInFeatures: UsageInFeatures,
  segmentKey: SegmentKey,
): Promise<Set<FeatureKey>> {
  const usedInFeatures = new Set<FeatureKey>();
 
  for (const featureKey in usageInFeatures) {
    if (usageInFeatures[featureKey].segments.has(segmentKey)) {
      usedInFeatures.add(featureKey);
    }
  }
 
  return usedInFeatures;
}
 
export interface AttributeUsage {
  features: Set<FeatureKey>;
  segments: Set<SegmentKey>;
}
 
export async function findAttributeUsage(
  usageInFeatures: UsageInFeatures,
  usageInSegments: UsageInSegments,
  attributeKey: AttributeKey,
): Promise<AttributeUsage> {
  const usedIn: AttributeUsage = {
    features: new Set<FeatureKey>(),
    segments: new Set<SegmentKey>(),
  };
 
  for (const featureKey in usageInFeatures) {
    if (usageInFeatures[featureKey].attributes.has(attributeKey)) {
      usedIn.features.add(featureKey);
    }
  }
 
  for (const segmentKey in usageInSegments) {
    if (usageInSegments[segmentKey].attributes.has(attributeKey)) {
      usedIn.segments.add(segmentKey);
    }
  }
 
  return usedIn;
}
 
export async function findUnusedSegments(
  deps: Dependencies,
  usageInFeatures: UsageInFeatures,
): Promise<Set<SegmentKey>> {
  const { datasource } = deps;
  const unusedSegments = new Set<SegmentKey>();
 
  const allSegmentKeys = await datasource.listSegments();
  const usedSegmentKeys = new Set<SegmentKey>();
 
  for (const featureKey in usageInFeatures) {
    usageInFeatures[featureKey].segments.forEach((segmentKey) => {
      usedSegmentKeys.add(segmentKey);
    });
  }
 
  allSegmentKeys.forEach((segmentKey) => {
    if (!usedSegmentKeys.has(segmentKey)) {
      unusedSegments.add(segmentKey);
    }
  });
 
  return unusedSegments;
}
 
export async function findUnusedAttributes(
  deps: Dependencies,
  usageInFeatures: UsageInFeatures,
  usageInSegments: UsageInSegments,
): Promise<Set<AttributeKey>> {
  const { datasource } = deps;
  const unusedAttributes = new Set<AttributeKey>();
 
  const allAttributeKeys = await datasource.listAttributes();
  const usedAttributeKeys = new Set<AttributeKey>();
 
  for (const featureKey in usageInFeatures) {
    usageInFeatures[featureKey].attributes.forEach((attributeKey) => {
      usedAttributeKeys.add(attributeKey);
    });
  }
 
  for (const segmentKey in usageInSegments) {
    usageInSegments[segmentKey].attributes.forEach((attributeKey) => {
      usedAttributeKeys.add(attributeKey);
    });
  }
 
  allAttributeKeys.forEach((attributeKey) => {
    if (!usedAttributeKeys.has(attributeKey)) {
      unusedAttributes.add(attributeKey);
    }
  });
 
  return unusedAttributes;
}
 
export interface FindUsageOptions {
  feature?: string;
  segment?: string;
  attribute?: string;
 
  unusedSegments?: boolean;
  unusedAttributes?: boolean;
 
  authors?: boolean;
}
 
export async function findUsageInProject(deps: Dependencies, options: FindUsageOptions) {
  const { datasource } = deps;
 
  console.log("");
  console.log(CLI_FORMAT_BOLD, "Finding Featurevisor usage");
  console.log("");
 
  const usageInFeatures = await findAllUsageInFeatures(deps);
  const usageInSegments = await findAllUsageInSegments(deps);
 
  // feature
  if (options.feature) {
    const usedInFeatures = await findFeatureUsage(usageInFeatures, options.feature);
 
    if (usedInFeatures.size === 0) {
      console.log(CLI_FORMAT_GREEN, `Feature "${options.feature}" is not used in any features.`);
    } else {
      console.log(CLI_FORMAT_BOLD, `Feature "${options.feature}" is used in these features`);
      console.log("");
 
      for (const featureKey of Array.from(usedInFeatures)) {
        if (options.authors) {
          const entries = await datasource.listHistoryEntries("feature", featureKey);
          const authors = Array.from(new Set(entries.map((entry) => entry.author)));
 
          console.log(
            `  ${colorize("•", CLI_COLOR_CYAN)} ${featureKey} ${colorize(`(Authors: ${authors.join(", ")})`, CLI_COLOR_DIM)}`,
          );
        } else {
          console.log(`  ${colorize("•", CLI_COLOR_CYAN)} ${featureKey}`);
        }
      }
    }
 
    return;
  }
 
  // segment
  if (options.segment) {
    const usedInFeatures = await findSegmentUsage(usageInFeatures, options.segment);
 
    if (usedInFeatures.size === 0) {
      console.log(CLI_FORMAT_GREEN, `Segment "${options.segment}" is not used in any features.`);
    } else {
      console.log(CLI_FORMAT_BOLD, `Segment "${options.segment}" is used in these features`);
      console.log("");
 
      for (const featureKey of Array.from(usedInFeatures)) {
        if (options.authors) {
          const entries = await datasource.listHistoryEntries("feature", featureKey);
          const authors = Array.from(new Set(entries.map((entry) => entry.author)));
 
          console.log(
            `  ${colorize("•", CLI_COLOR_CYAN)} ${featureKey} ${colorize(`(Authors: ${authors.join(", ")})`, CLI_COLOR_DIM)}`,
          );
        } else {
          console.log(`  ${colorize("•", CLI_COLOR_CYAN)} ${featureKey}`);
        }
      }
    }
 
    return;
  }
 
  // attribute
  if (options.attribute) {
    const usedIn = await findAttributeUsage(usageInFeatures, usageInSegments, options.attribute);
 
    if (usedIn.features.size === 0 && usedIn.segments.size === 0) {
      console.log(
        CLI_FORMAT_GREEN,
        `Attribute "${options.attribute}" is not used in any features or segments.`,
      );
 
      return;
    }
 
    if (usedIn.segments.size > 0) {
      console.log(CLI_FORMAT_BOLD, `Attribute "${options.attribute}" is used in these segments`);
      console.log("");
 
      for (const segmentKey of Array.from(usedIn.segments)) {
        if (options.authors) {
          const entries = await datasource.listHistoryEntries("segment", segmentKey);
          const authors = Array.from(new Set(entries.map((entry) => entry.author)));
 
          console.log(
            `  ${colorize("•", CLI_COLOR_CYAN)} ${segmentKey} ${colorize(`(Authors: ${authors.join(", ")})`, CLI_COLOR_DIM)}`,
          );
        } else {
          console.log(`  ${colorize("•", CLI_COLOR_CYAN)} ${segmentKey}`);
        }
      }
 
      // features affected by above segments
      const affectedFeatures = new Set<FeatureKey>();
 
      for (const segmentKey of Array.from(usedIn.segments)) {
        const featureKeys = await findSegmentUsage(usageInFeatures, segmentKey);
        featureKeys.forEach((featureKey) => affectedFeatures.add(featureKey));
      }
 
      if (affectedFeatures.size > 0) {
        console.log("");
        console.log(CLI_FORMAT_BOLD, "Segments above are used in these features");
        console.log("");
 
        for (const featureKey of Array.from(affectedFeatures)) {
          if (options.authors) {
            const entries = await datasource.listHistoryEntries("feature", featureKey);
            const authors = Array.from(new Set(entries.map((entry) => entry.author)));
 
            console.log(
              `  ${colorize("•", CLI_COLOR_CYAN)} ${featureKey} ${colorize(`(Authors: ${authors.join(", ")})`, CLI_COLOR_DIM)}`,
            );
          } else {
            console.log(`  ${colorize("•", CLI_COLOR_CYAN)} ${featureKey}`);
          }
        }
 
        console.log("");
      }
    }
 
    if (usedIn.features.size > 0) {
      console.log(
        CLI_FORMAT_BOLD,
        `Attribute "${options.attribute}" is used directly in these features`,
      );
      console.log("");
 
      for (const featureKey of Array.from(usedIn.features)) {
        if (options.authors) {
          const entries = await datasource.listHistoryEntries("feature", featureKey);
          const authors = Array.from(new Set(entries.map((entry) => entry.author)));
 
          console.log(
            `  ${colorize("•", CLI_COLOR_CYAN)} ${featureKey} ${colorize(`(Authors: ${authors.join(", ")})`, CLI_COLOR_DIM)}`,
          );
        } else {
          console.log(`  ${colorize("•", CLI_COLOR_CYAN)} ${featureKey}`);
        }
      }
 
      console.log("");
    }
 
    return;
  }
 
  // unused segments
  if (options.unusedSegments) {
    const unusedSegments = await findUnusedSegments(deps, usageInFeatures);
 
    if (unusedSegments.size === 0) {
      console.log(CLI_FORMAT_GREEN, "No unused segments found.");
    } else {
      console.log(CLI_FORMAT_YELLOW, "Unused segments");
      console.log("");
 
      for (const segmentKey of Array.from(unusedSegments)) {
        if (options.authors) {
          const entries = await datasource.listHistoryEntries("segment", segmentKey);
          const authors = Array.from(new Set(entries.map((entry) => entry.author)));
 
          console.log(
            `  ${colorize("•", CLI_COLOR_CYAN)} ${segmentKey} ${colorize(`(Authors: ${authors.join(", ")})`, CLI_COLOR_DIM)}`,
          );
        } else {
          console.log(`  ${colorize("•", CLI_COLOR_CYAN)} ${segmentKey}`);
        }
      }
    }
 
    return;
  }
 
  // unused attributes
  if (options.unusedAttributes) {
    const unusedAttributes = await findUnusedAttributes(deps, usageInFeatures, usageInSegments);
 
    if (unusedAttributes.size === 0) {
      console.log(CLI_FORMAT_GREEN, "No unused attributes found.");
    } else {
      console.log(CLI_FORMAT_YELLOW, "Unused attributes");
      console.log("");
 
      for (const attributeKey of Array.from(unusedAttributes)) {
        if (options.authors) {
          const entries = await datasource.listHistoryEntries("attribute", attributeKey);
          const authors = Array.from(new Set(entries.map((entry) => entry.author)));
 
          console.log(
            `  ${colorize("•", CLI_COLOR_CYAN)} ${attributeKey} ${colorize(`(Authors: ${authors.join(", ")})`, CLI_COLOR_DIM)}`,
          );
        } else {
          console.log(`  ${colorize("•", CLI_COLOR_CYAN)} ${attributeKey}`);
        }
      }
    }
 
    return;
  }
 
  console.log(CLI_FORMAT_YELLOW, "Please specify a feature, segment, attribute, or unused query.");
}
 
export const findUsagePlugin: Plugin = {
  command: "find-usage",
  handler: async ({ rootDirectoryPath, projectConfig, datasource, parsed }) => {
    const executions = await getProjectSetExecutions(projectConfig, datasource, parsed.set);
 
    for (const execution of executions) {
      printSetHeader(projectConfig, execution.set);
 
      await findUsageInProject(
        {
          rootDirectoryPath,
          projectConfig: execution.projectConfig,
          datasource: execution.datasource,
          options: parsed,
        },
        {
          feature: parsed.feature,
          segment: parsed.segment,
          attribute: parsed.attribute,
          unusedSegments: parsed.unusedSegments,
          unusedAttributes: parsed.unusedAttributes,
          authors: parsed.authors,
        },
      );
    }
  },
  examples: [
    {
      command: "find-usage --segment=<segmentKey>",
      description: "Find usage of a segment",
    },
    {
      command: "find-usage --attribute=<attributeKey>",
      description: "Find usage of an attribute",
    },
    {
      command: "find-usage --unused-segments",
      description: "Find unused segments",
    },
    {
      command: "find-usage --unused-attributes",
      description: "Find unused attributes",
    },
    {
      command: "find-usage --authors",
      description: "List authors of the usage",
    },
  ],
};