All files / src/promoter index.ts

80.26% Statements 419/522
68.01% Branches 253/372
80.34% Functions 94/117
83.65% Lines 389/465

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 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 12671x 1x                                     1x                 1x 1x                                                                                                                                         211x       124x 44x     80x       410x       407x                   353x 337x   337x   337x 47x 12x     47x     290x 120x   120x 255x           120x     170x 32x     170x       23x 12x     11x 11x 11x         3x 3x     3x     5x       3x 3x 3x 3x   2x     2x       2x       171x   171x             119x 112x             88x 88x   5x                                     34x                   34x           19x   19x 16x     3x   3x 1x     2x   2x                 17x 11x 11x 11x                               24x 24x       24x 12x 12x   12x 12x 12x                     73x 36x     37x         37x   37x 9x     47x                     16x 16x             16x   16x                                   16x 18x 18x 18x 1x     17x 17x                 16x                               14x 14x   11x 11x   11x 13x 1x     13x 12x   12x 1x 1x     11x               11x 12x         11x                         14x 14x                                                                                     14x 14x 14x 14x           14x 14x   14x 11x         21x             14x                               17x 17x 17x 17x 17x 17x 17x 1x         16x           16x                   16x 21x 16x 32x 1x 16x 1x 32x     16x 16x 16x 16x 16x 16x   16x 16x 2x 2x 1x       1x 1x     15x 6x 5x 10x 5x 5x 5x   10x 14x 14x 14x   14x   14x 3x   14x 8x       10x 1x       14x 14x 15x   15x 16x 16x 16x                     15x 2x 2x 4x 4x   2x 2x 4x         14x 14x 12x 12x   12x   12x 12x   12x             14x 14x 10x 10x   10x   10x 10x   10x             14x 28x 28x     14x                       73x 73x             73x   73x     88x 88x 88x   88x 1x                 1x     87x 87x   87x                   14x 25x 25x 25x       14x 12x 12x 12x       14x 1x 1x       1x       14x 10x 10x 10x       14x 15x 15x       15x   14x       14x 1x 1x 1x       14x 24x 24x     14x       6x 38x 28x     10x   10x   10x         10x   10x 1x 10x 5x 10x         21x 19x     2x 2x                 21x 19x     2x       2x 2x             1x 5x   1x                       81x                 81x 81x   81x         22x 22x     81x       82x 82x   82x               1x 1x 1x 1x   1x 1x 1x   1x 1x                                                     1x                                             1x         3x 7x 3x     1x 1x 1x   4x     1x     1x               1x 1x     1x       1x   1x     20x         21x 21x 21x   21x     21x 21x 21x   20x 20x 1x       19x           19x   17x 17x   17x 17x   17x               88x   14x 1x   4x   1x   1x         13x 6x     13x 81x   5x         13x 81x   19x         13x 81x   57x           13x 81x 81x 81x 81x 81x 81x 81x     13x                                 13x 1x     13x       2x 1x     1x 1x 2x   1x       1x       1x 1x 4x             1x     1x             1x 1x 1x 1x 1x 1x     1x     1x     1x     1x 1x 1x     1x 1x 1x 1x 1x   1x 1x 1x     1x   1x         1x 1x     1x     1x                         1x                                                                              
import * as fs from "fs";
import * as path from "path";
 
import type {
  Attribute,
  Condition,
  EntityType,
  GroupSegment,
  ParsedFeature,
  Rule,
  RulesByEnvironment,
  Schema,
  Segment,
  Group,
  Target,
  Test,
} from "@featurevisor/types";
 
import type { ProjectConfig } from "../config";
import type { Datasource } from "../datasource";
import { lintProject, type LintErrorItem } from "../linter";
import {
  CLI_COLOR_CYAN,
  CLI_COLOR_DIM,
  CLI_COLOR_GREEN,
  CLI_COLOR_YELLOW,
  CLI_FORMAT_BOLD,
  CLI_FORMAT_GREEN,
  colorize,
} from "../tester/cliFormat";
import { prettyDuration } from "../tester/prettyDuration";
import type { Plugin } from "../cli";
 
type ConflictPolicy = "source" | "destination" | "fail";
type PromotionAuditFormat = "json" | "markdown";
type EntityValue =
  | Attribute
  | Segment
  | ParsedFeature
  | Group
  | Record<string, unknown>
  | Schema
  | Target
  | Test;
 
interface PromotionConflict {
  type: EntityType;
  key: string;
  path: string;
  source: unknown;
  destination: unknown;
}
 
interface EntityPlan {
  type: EntityType;
  key: string;
  source: EntityValue;
  destination?: EntityValue;
  merged: EntityValue;
  conflicts: PromotionConflict[];
}
 
export interface PromoteProjectSetsOptions {
  from?: string;
  to?: string;
  includeFeatures?: string | string[];
  excludeFeatures?: string | string[];
  target?: string | string[];
  tag?: string | string[];
  conflicts?: ConflictPolicy;
  allowEmpty?: boolean;
  apply?: boolean;
  audit?: boolean | PromotionAuditFormat;
  showUnchanged?: boolean;
}
 
export interface PromoteProjectSetsResult {
  from: string;
  to: string;
  apply: boolean;
  duration: number;
  filters: {
    includeFeatures: string[];
    excludeFeatures: string[];
    targets: string[];
    tags: string[];
    conflicts: ConflictPolicy;
  };
  dependencies: Record<EntityType, number>;
  files: {
    created: string[];
    updated: string[];
    unchanged: string[];
  };
  conflicts: PromotionConflict[];
  auditFilePath?: string;
}
 
function isPromotable(entity: { promotable?: boolean } | undefined) {
  return entity?.promotable !== false;
}
 
function toArray(value: string | string[] | undefined): string[] {
  if (typeof value === "undefined") {
    return [];
  }
 
  return Array.isArray(value) ? value : [value];
}
 
function isPlainObject(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
 
function deepEqual(left: unknown, right: unknown): boolean {
  return JSON.stringify(left) === JSON.stringify(right);
}
 
function deepMergeWithPolicy(
  destination: unknown,
  source: unknown,
  policy: ConflictPolicy,
  conflicts: Array<Omit<PromotionConflict, "type" | "key">>,
  pathSegments: string[] = [],
): unknown {
  if (typeof destination === "undefined") return source;
  Iif (typeof source === "undefined") return destination;
 
  const conflictPath = pathSegments.join(".") || "<root>";
 
  if (Array.isArray(destination) && Array.isArray(source)) {
    if (!deepEqual(destination, source)) {
      conflicts.push({ path: conflictPath, source, destination });
    }
 
    return policy === "destination" ? destination : source;
  }
 
  if (isPlainObject(destination) && isPlainObject(source)) {
    const result: Record<string, unknown> = { ...destination };
 
    for (const key of Object.keys(source)) {
      result[key] = deepMergeWithPolicy(result[key], source[key], policy, conflicts, [
        ...pathSegments,
        key,
      ]);
    }
 
    return result;
  }
 
  if (!deepEqual(destination, source)) {
    conflicts.push({ path: conflictPath, source, destination });
  }
 
  return policy === "destination" ? destination : source;
}
 
function matchesPattern(key: string, patterns: string[]) {
  if (patterns.length === 0) {
    return false;
  }
 
  return patterns.some((pattern) => {
    const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
    return new RegExp(`^${escaped}$`).test(key);
  });
}
 
function matchesTags(candidateTags: string[], selector: Target["tags"]): boolean {
  Iif (!selector) return true;
  Iif (Array.isArray(selector)) {
    return selector.some((tag) => candidateTags.includes(tag));
  }
  Iif ("or" in selector) {
    return selector.or.some((tag) => candidateTags.includes(tag));
  }
  return selector.and.every((tag) => candidateTags.includes(tag));
}
 
function matchesTarget(featureKey: string, feature: ParsedFeature, target: Target): boolean {
  const featureTags = feature.tags || [];
  Iif (feature.archived === true) return false;
  Iif (target.tag && !featureTags.includes(target.tag)) return false;
  if (target.tags && !matchesTags(featureTags, target.tags)) return false;
 
  const included = target.includeFeatures
    ? matchesPattern(featureKey, toArray(target.includeFeatures))
    : true;
  const excluded = target.excludeFeatures
    ? matchesPattern(featureKey, toArray(target.excludeFeatures))
    : false;
 
  return included && !excluded;
}
 
function withoutKey<T extends Record<string, unknown>>(entity: T): T {
  const { key: _key, ...rest } = entity; // eslint-disable-line @typescript-eslint/no-unused-vars
 
  return rest as T;
}
 
async function safeRead<T>(
  keys: string[],
  read: (key: string) => Promise<T>,
): Promise<Record<string, T>> {
  const entries = await Promise.all(keys.map(async (key) => [key, await read(key)] as const));
  return Object.fromEntries(entries);
}
 
async function readDestination<T>(
  key: string,
  read: (key: string) => Promise<T>,
): Promise<T | undefined> {
  try {
    return await read(key);
  } catch {
    return undefined;
  }
}
 
function formatLintPreflightErrors(set: string, errors: LintErrorItem[]) {
  const preview = errors
    .slice(0, 5)
    .map((error) => `${error.filePath}: ${error.message}`)
    .join("\n");
  const suffix = errors.length > 5 ? `\n...and ${errors.length - 5} more` : "";
 
  return `Set "${set}" failed preflight lint with ${errors.length} error(s).\n${preview}${suffix}`;
}
 
async function assertSetLintsClean(
  set: string,
  projectConfig: ProjectConfig,
  datasource: Datasource,
) {
  const result = await lintProject(
    {
      rootDirectoryPath: path.resolve(projectConfig.setsDirectoryPath, ".."),
      projectConfig,
      datasource,
      options: {},
    },
    { json: true },
  );
 
  Iif (result.hasError) {
    throw new Error(formatLintPreflightErrors(set, result.errors));
  }
}
 
function assertAllowedPromotionFlow(projectConfig: ProjectConfig, from: string, to: string) {
  const allowedFlows = projectConfig.promotionFlows;
 
  if (typeof allowedFlows === "undefined") {
    return;
  }
 
  const isAllowed = allowedFlows.some((flow) => flow.from === from && flow.to === to);
 
  if (isAllowed) {
    return;
  }
 
  const allowedList = allowedFlows.map((flow) => `${flow.from} -> ${flow.to}`).join(", ") || "none";
 
  throw new Error(
    `Promotion from "${from}" to "${to}" is not allowed by this project's configured promotionFlows.\nAllowed flows: ${allowedList}.\nChoose one of the allowed promotion paths or update featurevisor.config.js if this flow should be permitted.`,
  );
}
 
function collectGroupSegmentKeys(
  value: GroupSegment | GroupSegment[] | "*" | undefined,
  result: Set<string>,
) {
  if (!value || value === "*") return;
  Eif (typeof value === "string") {
    result.add(value);
    return;
  }
  if (Array.isArray(value)) {
    value.forEach((entry) => collectGroupSegmentKeys(entry, result));
    return;
  }
  if ("and" in value) value.and.forEach((entry) => collectGroupSegmentKeys(entry, result));
  if ("or" in value) value.or.forEach((entry) => collectGroupSegmentKeys(entry, result));
  if ("not" in value) value.not.forEach((entry) => collectGroupSegmentKeys(entry, result));
}
 
function collectConditionDependencies(
  value: Condition | Condition[] | "*" | undefined,
  segments: Set<string>,
  attributes: Set<string>,
) {
  Iif (!value || value === "*") return;
  Iif (typeof value === "string") {
    segments.add(value);
    return;
  }
  if (Array.isArray(value)) {
    value.forEach((entry) => collectConditionDependencies(entry, segments, attributes));
    return;
  }
  Eif ("attribute" in value) {
    attributes.add(value.attribute.split(".")[0]);
    return;
  }
  if ("and" in value)
    value.and.forEach((entry) => collectConditionDependencies(entry, segments, attributes));
  if ("or" in value)
    value.or.forEach((entry) => collectConditionDependencies(entry, segments, attributes));
  if ("not" in value)
    value.not.forEach((entry) => collectConditionDependencies(entry, segments, attributes));
}
 
function collectSchemaReferences(value: unknown, schemas: Set<string>) {
  if (!value || typeof value !== "object") {
    return;
  }
 
  Iif (Array.isArray(value)) {
    value.forEach((entry) => collectSchemaReferences(entry, schemas));
    return;
  }
 
  const record = value as Record<string, unknown>;
 
  if (typeof record.schema === "string") {
    schemas.add(record.schema);
  }
 
  Object.values(record).forEach((entry) => collectSchemaReferences(entry, schemas));
}
 
function collectFeatureDependencies(
  feature: ParsedFeature,
  features: Record<string, ParsedFeature>,
  featureKeys: Set<string>,
  segmentKeys: Set<string>,
  attributeKeys: Set<string>,
  schemaKeys: Set<string>,
) {
  if (typeof feature.bucketBy === "string") {
    attributeKeys.add(feature.bucketBy);
  } else Eif (Array.isArray(feature.bucketBy)) {
    feature.bucketBy.forEach((attributeKey) => attributeKeys.add(attributeKey));
  } else if (feature.bucketBy && "or" in feature.bucketBy) {
    feature.bucketBy.or.forEach((attributeKey) => attributeKeys.add(attributeKey));
  }
 
  collectSchemaReferences(feature.variablesSchema, schemaKeys);
 
  for (const required of feature.required || []) {
    const requiredKey = typeof required === "string" ? required : required.key;
    if (!featureKeys.has(requiredKey)) {
      featureKeys.add(requiredKey);
      const requiredFeature = features[requiredKey];
      if (requiredFeature) {
        collectFeatureDependencies(
          requiredFeature,
          features,
          featureKeys,
          segmentKeys,
          attributeKeys,
          schemaKeys,
        );
      }
    }
  }
 
  for (const rules of Object.values((feature.rules || {}) as any)) {
    const ruleEntries = Array.isArray(rules) ? rules : [rules];
    for (const rule of ruleEntries) {
      if (!isPromotable(rule)) {
        continue;
      }
 
      collectGroupSegmentKeys(rule?.segments, segmentKeys);
      Object.values(rule?.variableOverrides || {}).forEach((overrides: any) => {
        (overrides || []).forEach((override: any) => {
          collectGroupSegmentKeys(override.segments, segmentKeys);
          collectConditionDependencies(override.conditions, segmentKeys, attributeKeys);
        });
      });
    }
  }
 
  for (const force of Object.values((feature.force || {}) as any)) {
    const forceEntries = Array.isArray(force) ? force : [force];
    for (const forceEntry of forceEntries) {
      collectGroupSegmentKeys(forceEntry?.segments, segmentKeys);
      collectConditionDependencies(forceEntry?.conditions, segmentKeys, attributeKeys);
    }
  }
}
 
function mergeRuleArray(
  destination: Rule[] | undefined,
  source: Rule[] | undefined,
  policy: ConflictPolicy,
  conflicts: Array<Omit<PromotionConflict, "type" | "key">>,
  pathSegments: string[],
) {
  Iif (typeof source === "undefined") return destination;
  if (typeof destination === "undefined") return source.filter((rule) => isPromotable(rule));
 
  const mergedRuleKeys = new Set<string>();
  const mergedRules: Rule[] = [];
 
  for (const sourceRule of source) {
    if (!isPromotable(sourceRule)) {
      continue;
    }
 
    const destinationRule = destination.find((rule) => rule.key === sourceRule.key);
    mergedRuleKeys.add(sourceRule.key);
 
    if (destinationRule && !isPromotable(destinationRule)) {
      mergedRules.push(destinationRule);
      continue;
    }
 
    mergedRules.push(
      deepMergeWithPolicy(destinationRule, sourceRule, policy, conflicts, [
        ...pathSegments,
        sourceRule.key,
      ]) as Rule,
    );
  }
 
  for (const destinationRule of destination) {
    Iif (!mergedRuleKeys.has(destinationRule.key)) {
      mergedRules.push(destinationRule);
    }
  }
 
  return mergedRules;
}
 
function isRulesByEnvironment(value: ParsedFeature["rules"]): value is RulesByEnvironment {
  return isPlainObject(value) && !Array.isArray(value);
}
 
function mergeRules(
  destination: ParsedFeature["rules"] | undefined,
  source: ParsedFeature["rules"] | undefined,
  policy: ConflictPolicy,
  conflicts: Array<Omit<PromotionConflict, "type" | "key">>,
) {
  Eif (Array.isArray(source) || Array.isArray(destination)) {
    return mergeRuleArray(
      Array.isArray(destination) ? destination : undefined,
      Array.isArray(source) ? source : undefined,
      policy,
      conflicts,
      ["rules"],
    );
  }
 
  if (isRulesByEnvironment(source) || isRulesByEnvironment(destination)) {
    const environmentKeys = new Set([
      ...Object.keys((destination || {}) as RulesByEnvironment),
      ...Object.keys((source || {}) as RulesByEnvironment),
    ]);
    const result: RulesByEnvironment = {};
 
    for (const environment of Array.from(environmentKeys).sort()) {
      const merged = mergeRuleArray(
        (destination as RulesByEnvironment | undefined)?.[environment],
        (source as RulesByEnvironment | undefined)?.[environment],
        policy,
        conflicts,
        ["rules", environment],
      );
 
      if (typeof merged !== "undefined") {
        result[environment] = merged;
      }
    }
 
    return Object.keys(result).length > 0 ? result : undefined;
  }
 
  return source;
}
 
function mergeFeature(
  featureKey: string,
  destination: ParsedFeature | undefined,
  source: ParsedFeature,
  policy: ConflictPolicy,
  conflicts: PromotionConflict[],
): ParsedFeature {
  const sourceWithoutRules = { ...source, rules: undefined };
  const destinationWithoutRules = destination ? { ...destination, rules: undefined } : undefined;
  const featureConflicts: Array<Omit<PromotionConflict, "type" | "key">> = [];
  const mergedFeature = deepMergeWithPolicy(
    destinationWithoutRules,
    sourceWithoutRules,
    policy,
    featureConflicts,
  ) as ParsedFeature;
  const ruleConflicts: Array<Omit<PromotionConflict, "type" | "key">> = [];
  const mergedRules = mergeRules(destination?.rules, source.rules, policy, ruleConflicts);
 
  conflicts.push(
    ...featureConflicts.map((conflict) => ({
      type: "feature" as const,
      key: featureKey,
      ...conflict,
    })),
    ...ruleConflicts.map((conflict) => ({
      type: "feature" as const,
      key: featureKey,
      ...conflict,
    })),
  );
 
  return {
    ...mergedFeature,
    rules: mergedRules,
  };
}
 
async function getPromotionPlan(
  sourceDatasource: Datasource,
  destinationDatasource: Datasource,
  options: Required<
    Pick<
      PromoteProjectSetsOptions,
      "includeFeatures" | "excludeFeatures" | "target" | "tag" | "allowEmpty" | "conflicts"
    >
  >,
) {
  const includeFeatures = toArray(options.includeFeatures);
  const excludeFeatures = toArray(options.excludeFeatures);
  const targetSelectors = toArray(options.target);
  const tagSelectors = toArray(options.tag);
  const availableTags = sourceDatasource.getConfig().tags;
  const unknownTag = tagSelectors.find((tag) => !availableTags.includes(tag));
  if (unknownTag) {
    throw new Error(
      `Unknown source tag "${unknownTag}". Available tags: ${availableTags.join(", ") || "none"}.`,
    );
  }
  const hasNoFilters =
    includeFeatures.length === 0 &&
    excludeFeatures.length === 0 &&
    targetSelectors.length === 0 &&
    tagSelectors.length === 0;
 
  const [featureKeys, segmentKeys, attributeKeys, groupKeys, schemaKeys, targetKeys, testKeys] =
    await Promise.all([
      sourceDatasource.listFeatures(),
      sourceDatasource.listSegments(),
      sourceDatasource.listAttributes(),
      sourceDatasource.listGroups(),
      sourceDatasource.listSchemas(),
      sourceDatasource.listTargets(),
      sourceDatasource.listTests(),
    ]);
 
  const [features, segments, attributes, groups, schemas, targets, tests] = await Promise.all([
    safeRead<ParsedFeature>(featureKeys, (key) => sourceDatasource.readFeature(key)),
    safeRead<Segment>(segmentKeys, (key) => sourceDatasource.readSegment(key)),
    safeRead<Attribute>(attributeKeys, (key) => sourceDatasource.readAttribute(key)),
    safeRead<Group>(groupKeys, (key) => sourceDatasource.readGroup(key)),
    safeRead<Schema>(schemaKeys, (key) => sourceDatasource.readSchema(key)),
    safeRead<Target>(targetKeys, (key) => sourceDatasource.readTarget(key)),
    safeRead<Test>(testKeys, (key) => sourceDatasource.readTest(key)),
  ]);
 
  const promotedFeatureKeys = new Set<string>();
  const promotedSegmentKeys = new Set<string>();
  const promotedAttributeKeys = new Set<string>();
  const promotedGroupKeys = new Set<string>();
  const promotedSchemaKeys = new Set<string>();
  const promotedTargetKeys = new Set<string>();
 
  const selectedTargets: Target[] = [];
  for (const key of targetSelectors) {
    const target = targets[key];
    if (!target) {
      throw new Error(
        `Unknown source target "${key}". Available targets: ${targetKeys.join(", ") || "none"}.`,
      );
    }
    selectedTargets.push(target);
    promotedTargetKeys.add(key);
  }
 
  if (hasNoFilters) {
    featureKeys.forEach((key) => promotedFeatureKeys.add(key));
    segmentKeys.forEach((key) => promotedSegmentKeys.add(key));
    attributeKeys.forEach((key) => promotedAttributeKeys.add(key));
    groupKeys.forEach((key) => promotedGroupKeys.add(key));
    schemaKeys.forEach((key) => promotedSchemaKeys.add(key));
    targetKeys.forEach((key) => promotedTargetKeys.add(key));
  } else {
    for (const key of featureKeys) {
      const feature = features[key];
      const matchesIncludes = includeFeatures.length === 0 || matchesPattern(key, includeFeatures);
      const matchesExcludes = matchesPattern(key, excludeFeatures);
      const matchesSelectedTags =
        tagSelectors.length === 0 || tagSelectors.some((tag) => (feature.tags || []).includes(tag));
      const matchesSelectedTargets =
        selectedTargets.length === 0 ||
        selectedTargets.some((target) => matchesTarget(key, feature, target));
 
      if (matchesIncludes && !matchesExcludes && matchesSelectedTags && matchesSelectedTargets) {
        promotedFeatureKeys.add(key);
      }
    }
 
    if (promotedFeatureKeys.size === 0 && !options.allowEmpty) {
      throw new Error("No source features matched the promotion filters.");
    }
  }
 
  let previousFeatureCount = -1;
  while (previousFeatureCount !== promotedFeatureKeys.size) {
    previousFeatureCount = promotedFeatureKeys.size;
 
    for (const key of Array.from(promotedFeatureKeys)) {
      const feature = features[key];
      Eif (feature) {
        collectFeatureDependencies(
          feature,
          features,
          promotedFeatureKeys,
          promotedSegmentKeys,
          promotedAttributeKeys,
          promotedSchemaKeys,
        );
      }
    }
 
    for (const key of groupKeys) {
      const group = groups[key];
      const groupFeatureKeys = group.slots
        .map((slot) => slot.feature)
        .filter((featureKey): featureKey is string => typeof featureKey === "string");
 
      Eif (groupFeatureKeys.some((featureKey) => promotedFeatureKeys.has(featureKey))) {
        promotedGroupKeys.add(key);
        groupFeatureKeys.forEach((featureKey) => promotedFeatureKeys.add(featureKey));
      }
    }
  }
 
  const pendingSegments = Array.from(promotedSegmentKeys);
  for (let index = 0; index < pendingSegments.length; index++) {
    const segmentKey = pendingSegments[index];
    const segment = segments[segmentKey];
 
    Iif (!segment) continue;
 
    const beforeSize = promotedSegmentKeys.size;
    collectConditionDependencies(segment.conditions, promotedSegmentKeys, promotedAttributeKeys);
 
    Iif (promotedSegmentKeys.size > beforeSize) {
      pendingSegments.push(
        ...Array.from(promotedSegmentKeys).filter((key) => !pendingSegments.includes(key)),
      );
    }
  }
 
  const pendingSchemas = Array.from(promotedSchemaKeys);
  for (let index = 0; index < pendingSchemas.length; index++) {
    const schemaKey = pendingSchemas[index];
    const schema = schemas[schemaKey];
 
    Iif (!schema) continue;
 
    const beforeSize = promotedSchemaKeys.size;
    collectSchemaReferences(schema, promotedSchemaKeys);
 
    Iif (promotedSchemaKeys.size > beforeSize) {
      pendingSchemas.push(
        ...Array.from(promotedSchemaKeys).filter((key) => !pendingSchemas.includes(key)),
      );
    }
  }
 
  const promotedTestKeys = testKeys.filter((key) => {
    const test = tests[key] as any;
    return promotedFeatureKeys.has(test.feature) || promotedSegmentKeys.has(test.segment);
  });
 
  const plans: EntityPlan[] = [];
 
  async function plan<T extends EntityValue>(
    type: EntityType,
    key: string,
    source: T,
    readDestinationEntity: (key: string) => Promise<T>,
    merge: (destination: T | undefined, source: T, conflicts: PromotionConflict[]) => T = (
      destination,
      sourceValue,
      conflicts,
    ) => {
      const entityConflicts: Array<Omit<PromotionConflict, "type" | "key">> = [];
      const merged = deepMergeWithPolicy(
        destination,
        sourceValue,
        options.conflicts,
        entityConflicts,
      ) as T;
 
      conflicts.push(...entityConflicts.map((conflict) => ({ type, key, ...conflict })));
 
      return merged;
    },
  ) {
    const cleanedSource = withoutKey(source as any) as T;
    const destination = await readDestination<T>(key, readDestinationEntity);
    const cleanedDestination = destination ? (withoutKey(destination as any) as T) : undefined;
 
    if (cleanedDestination && (!isPromotable(cleanedSource) || !isPromotable(cleanedDestination))) {
      plans.push({
        type,
        key,
        source: cleanedSource,
        destination: cleanedDestination,
        merged: cleanedDestination,
        conflicts: [],
      });
 
      return;
    }
 
    const conflicts: PromotionConflict[] = [];
    const merged = merge(cleanedDestination, cleanedSource, conflicts);
 
    plans.push({
      type,
      key,
      source: cleanedSource,
      destination: cleanedDestination,
      merged,
      conflicts,
    });
  }
 
  for (const key of Array.from(promotedAttributeKeys).sort()) {
    Eif (attributes[key])
      await plan("attribute", key, attributes[key], (entryKey) =>
        destinationDatasource.readAttribute(entryKey),
      );
  }
 
  for (const key of Array.from(promotedSegmentKeys).sort()) {
    Eif (segments[key])
      await plan("segment", key, segments[key], (entryKey) =>
        destinationDatasource.readSegment(entryKey),
      );
  }
 
  for (const key of Array.from(promotedGroupKeys).sort()) {
    Eif (groups[key])
      await plan(
        "group",
        key,
        groups[key] as any,
        (entryKey) => destinationDatasource.readGroup(entryKey) as any,
      );
  }
 
  for (const key of Array.from(promotedSchemaKeys).sort()) {
    Eif (schemas[key])
      await plan("schema", key, schemas[key], (entryKey) =>
        destinationDatasource.readSchema(entryKey),
      );
  }
 
  for (const key of Array.from(promotedFeatureKeys).sort()) {
    Eif (features[key])
      await plan(
        "feature",
        key,
        features[key],
        (entryKey) => destinationDatasource.readFeature(entryKey),
        (destination, source, conflicts) =>
          mergeFeature(key, destination, source, options.conflicts, conflicts),
      );
  }
 
  for (const key of Array.from(promotedTargetKeys).sort()) {
    Eif (targets[key])
      await plan("target", key, targets[key], (entryKey) =>
        destinationDatasource.readTarget(entryKey),
      );
  }
 
  for (const key of promotedTestKeys.sort()) {
    Eif (tests[key])
      await plan("test", key, tests[key], (entryKey) => destinationDatasource.readTest(entryKey));
  }
 
  return plans;
}
 
async function writePlan(destinationDatasource: Datasource, plans: EntityPlan[]) {
  for (const plan of plans) {
    if (deepEqual(plan.destination, plan.merged)) {
      continue;
    }
 
    Iif (plan.type === "attribute")
      await destinationDatasource.writeAttribute(plan.key, plan.merged as Attribute);
    Iif (plan.type === "segment")
      await destinationDatasource.writeSegment(plan.key, plan.merged as Segment);
    Iif (plan.type === "group")
      await destinationDatasource.writeGroup(
        plan.key,
        plan.merged as Record<string, unknown> as any,
      );
    Iif (plan.type === "schema")
      await destinationDatasource.writeSchema(plan.key, plan.merged as Schema);
    if (plan.type === "target")
      await destinationDatasource.writeTarget(plan.key, plan.merged as Target);
    if (plan.type === "feature")
      await destinationDatasource.writeFeature(plan.key, plan.merged as ParsedFeature);
    if (plan.type === "test") await destinationDatasource.writeTest(plan.key, plan.merged as Test);
  }
}
 
function normalizeConflictPolicy(value: unknown): ConflictPolicy {
  if (typeof value === "undefined" || value === false) {
    return "source";
  }
 
  Eif (value === "source" || value === "destination" || value === "fail") {
    return value;
  }
 
  throw new Error(
    `Invalid --conflicts value "${String(value)}". Use source, destination, or fail.`,
  );
}
 
function normalizeAuditFormat(value: unknown): PromotionAuditFormat | false {
  if (typeof value === "undefined" || value === false || value === "false") {
    return false;
  }
 
  Iif (value === true || value === "true") {
    return "json";
  }
 
  Eif (value === "json" || value === "markdown") {
    return value;
  }
 
  throw new Error(`Invalid --audit value "${String(value)}". Use json or markdown.`);
}
 
function getTimestamp() {
  const date = new Date();
  const pad = (value: number) => (value < 10 ? `0${value}` : String(value));
 
  return [
    date.getUTCFullYear(),
    pad(date.getUTCMonth() + 1),
    pad(date.getUTCDate()),
    "T",
    pad(date.getUTCHours()),
    pad(date.getUTCMinutes()),
    pad(date.getUTCSeconds()),
  ].join("");
}
 
function getEntityFilePath(projectConfig: ProjectConfig, type: EntityType, key: string) {
  const directories: Record<EntityType, string> = {
    attribute: projectConfig.attributesDirectoryPath,
    segment: projectConfig.segmentsDirectoryPath,
    feature: projectConfig.featuresDirectoryPath,
    group: projectConfig.groupsDirectoryPath,
    schema: projectConfig.schemasDirectoryPath,
    target: projectConfig.targetsDirectoryPath,
    test: projectConfig.testsDirectoryPath,
  };
  const extension = (projectConfig.parser as any).extension || "yml";
  const pathSegments = key.split(projectConfig.namespaceCharacter);
 
  if (
    type === "test" &&
    pathSegments.length > 1 &&
    pathSegments[pathSegments.length - 1] === "spec"
  ) {
    pathSegments[pathSegments.length - 2] = `${pathSegments[pathSegments.length - 2]}.spec`;
    pathSegments.pop();
  }
 
  return path.join(directories[type], ...pathSegments) + `.${extension}`;
}
 
function formatProjectPath(projectConfig: ProjectConfig, filePath: string) {
  const root = path.resolve(projectConfig.setsDirectoryPath, "..");
  const relative = path.relative(root, filePath);
 
  return relative.startsWith("..") ? filePath : relative;
}
 
async function getPromotionAuditFilePath(
  projectConfig: ProjectConfig,
  result: PromoteProjectSetsResult,
  format: PromotionAuditFormat,
) {
  const extension = format === "markdown" ? "md" : "json";
  const baseFileName = `${getTimestamp()}-${result.from}-to-${result.to}`;
  const directoryPath = path.join(projectConfig.stateDirectoryPath, "promotions");
  let suffix = 0;
 
  while (true) {
    const fileName = `${baseFileName}${suffix === 0 ? "" : `-${suffix}`}.${extension}`;
    const filePath = path.join(directoryPath, fileName);
 
    Eif (!fs.existsSync(filePath)) {
      return filePath;
    }
 
    suffix++;
  }
}
 
function getAuditPayload(result: PromoteProjectSetsResult) {
  return {
    from: result.from,
    to: result.to,
    apply: result.apply,
    filters: result.filters,
    dependencies: result.dependencies,
    files: result.files,
    conflicts: result.conflicts.map((conflict) => ({
      type: conflict.type,
      key: conflict.key,
      path: conflict.path,
      source: conflict.source,
      destination: conflict.destination,
    })),
    duration: result.duration,
  };
}
 
function stringifyMarkdownAudit(result: PromoteProjectSetsResult) {
  const lines = [
    "# Featurevisor Promotion",
    "",
    `- From: ${result.from}`,
    `- To: ${result.to}`,
    `- Mode: ${result.apply ? "apply" : "preview"}`,
    `- Conflicts: ${result.filters.conflicts}`,
    `- Duration: ${prettyDuration(result.duration)}`,
    "",
    "## Dependencies",
    "",
    `- Attributes: ${result.dependencies.attribute}`,
    `- Segments: ${result.dependencies.segment}`,
    `- Features: ${result.dependencies.feature}`,
    `- Groups: ${result.dependencies.group}`,
    `- Schemas: ${result.dependencies.schema}`,
    `- Targets: ${result.dependencies.target}`,
    `- Tests: ${result.dependencies.test}`,
    "",
    "## Files",
    "",
  ];
 
  for (const [label, files] of [
    ["Created", result.files.created],
    ["Updated", result.files.updated],
    ["Unchanged", result.files.unchanged],
  ] as const) {
    lines.push(`### ${label}`, "");
    lines.push(...(files.length > 0 ? files.map((filePath) => `- ${filePath}`) : ["- None"]));
    lines.push("");
  }
 
  Eif (result.conflicts.length > 0) {
    lines.push("## Conflicts", "");
    lines.push(
      ...result.conflicts.map(
        (conflict) => `- ${conflict.type} ${conflict.key} at ${conflict.path}`,
      ),
    );
    lines.push("");
  }
 
  return `${lines.join("\n")}\n`;
}
 
async function writePromotionAudit(
  projectConfig: ProjectConfig,
  result: PromoteProjectSetsResult,
  format: PromotionAuditFormat,
) {
  const filePath = await getPromotionAuditFilePath(projectConfig, result, format);
  await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
 
  const content =
    format === "markdown"
      ? stringifyMarkdownAudit(result)
      : `${JSON.stringify(getAuditPayload(result), null, 2)}\n`;
 
  await fs.promises.writeFile(filePath, content);
 
  return formatProjectPath(projectConfig, filePath);
}
 
export async function promoteProjectSets(
  projectConfig: ProjectConfig,
  datasource: Datasource,
  options: PromoteProjectSetsOptions,
): Promise<PromoteProjectSetsResult> {
  const startTime = Date.now();
  const conflictPolicy = normalizeConflictPolicy(options.conflicts);
  const auditFormat = normalizeAuditFormat(options.audit);
 
  Iif (!projectConfig.sets) {
    throw new Error("Promotion is only available when `sets: true` is configured.");
  }
  Iif (!options.from) throw new Error("Pass --from=<set>.");
  Iif (!options.to) throw new Error("Pass --to=<set>.");
  if (options.from === options.to) throw new Error("--from and --to must be different sets.");
 
  const sets = await datasource.listSets();
  if (!sets.includes(options.from)) {
    throw new Error(
      `Unknown source set "${options.from}". Available sets: ${sets.join(", ") || "none"}.`,
    );
  }
  Iif (!sets.includes(options.to)) {
    throw new Error(
      `Unknown destination set "${options.to}". Available sets: ${sets.join(", ") || "none"}.`,
    );
  }
 
  assertAllowedPromotionFlow(projectConfig, options.from, options.to);
 
  const sourceDatasource = datasource.forSet(options.from);
  const destinationDatasource = datasource.forSet(options.to);
 
  await assertSetLintsClean(options.from, sourceDatasource.getConfig(), sourceDatasource);
  await assertSetLintsClean(options.to, destinationDatasource.getConfig(), destinationDatasource);
 
  const plans = await getPromotionPlan(sourceDatasource, destinationDatasource, {
    includeFeatures: options.includeFeatures || [],
    excludeFeatures: options.excludeFeatures || [],
    target: options.target || [],
    tag: options.tag || [],
    allowEmpty: options.allowEmpty === true,
    conflicts: conflictPolicy,
  });
  const conflicts = plans.flatMap((plan) => plan.conflicts);
 
  if (conflictPolicy === "fail" && conflicts.length > 0) {
    const preview = conflicts
      .slice(0, 5)
      .map((conflict) => `${conflict.type} "${conflict.key}" at ${conflict.path}`)
      .join("\n");
    const suffix = conflicts.length > 5 ? `\n...and ${conflicts.length - 5} more` : "";
 
    throw new Error(
      `Promotion has ${conflicts.length} conflict(s) and --conflicts=fail was used.\n${preview}${suffix}`,
    );
  }
 
  if (options.apply === true) {
    await writePlan(destinationDatasource, plans);
  }
 
  const created = plans
    .filter((plan) => !plan.destination)
    .map((plan) =>
      formatProjectPath(
        projectConfig,
        getEntityFilePath(destinationDatasource.getConfig(), plan.type, plan.key),
      ),
    );
  const updated = plans
    .filter((plan) => plan.destination && !deepEqual(plan.destination, plan.merged))
    .map((plan) =>
      formatProjectPath(
        projectConfig,
        getEntityFilePath(destinationDatasource.getConfig(), plan.type, plan.key),
      ),
    );
  const unchanged = plans
    .filter((plan) => plan.destination && deepEqual(plan.destination, plan.merged))
    .map((plan) =>
      formatProjectPath(
        projectConfig,
        getEntityFilePath(destinationDatasource.getConfig(), plan.type, plan.key),
      ),
    );
 
  const dependencies = {
    attribute: plans.filter((plan) => plan.type === "attribute").length,
    segment: plans.filter((plan) => plan.type === "segment").length,
    feature: plans.filter((plan) => plan.type === "feature").length,
    group: plans.filter((plan) => plan.type === "group").length,
    schema: plans.filter((plan) => plan.type === "schema").length,
    target: plans.filter((plan) => plan.type === "target").length,
    test: plans.filter((plan) => plan.type === "test").length,
  };
 
  const result: PromoteProjectSetsResult = {
    from: options.from,
    to: options.to,
    apply: options.apply === true,
    duration: Date.now() - startTime,
    filters: {
      includeFeatures: toArray(options.includeFeatures),
      excludeFeatures: toArray(options.excludeFeatures),
      targets: toArray(options.target),
      tags: toArray(options.tag),
      conflicts: conflictPolicy,
    },
    dependencies,
    files: { created, updated, unchanged },
    conflicts,
  };
 
  if (result.apply && auditFormat) {
    result.auditFilePath = await writePromotionAudit(projectConfig, result, auditFormat);
  }
 
  return result;
}
 
function printFileGroup(label: string, files: string[], color: number) {
  if (files.length === 0) {
    return;
  }
 
  console.log(CLI_FORMAT_BOLD, label);
  for (const filePath of files) {
    console.log(`  ${colorize(filePath, color)}`);
  }
  console.log("");
}
 
function printConflictPreview(conflicts: PromotionConflict[]) {
  Iif (conflicts.length === 0) {
    return;
  }
 
  console.log(CLI_FORMAT_BOLD, "Conflicts");
  for (const conflict of conflicts.slice(0, 10)) {
    console.log(
      `  ${colorize(conflict.type, CLI_COLOR_YELLOW)} ${conflict.key} ${colorize(
        conflict.path,
        CLI_COLOR_DIM,
      )}`,
    );
  }
  Iif (conflicts.length > 10) {
    console.log(`  ${colorize(`...and ${conflicts.length - 10} more`, CLI_COLOR_DIM)}`);
  }
  console.log("");
}
 
function printPromoteResult(
  result: PromoteProjectSetsResult,
  options: { showUnchanged?: boolean } = {},
) {
  console.log("");
  console.log(CLI_FORMAT_BOLD, "Promoting Featurevisor set definitions");
  console.log(`  From: ${result.from}`);
  console.log(`  To:   ${result.to}`);
  console.log(`  Mode: ${result.apply ? "apply" : "preview"}`);
  Iif (result.filters.includeFeatures.length > 0) {
    console.log(`  Include features: ${result.filters.includeFeatures.join(", ")}`);
  }
  Iif (result.filters.excludeFeatures.length > 0) {
    console.log(`  Exclude features: ${result.filters.excludeFeatures.join(", ")}`);
  }
  Iif (result.filters.targets.length > 0) {
    console.log(`  Targets: ${result.filters.targets.join(", ")}`);
  }
  Iif (result.filters.tags.length > 0) {
    console.log(`  Tags: ${result.filters.tags.join(", ")}`);
  }
  console.log(`  Conflict policy: ${result.filters.conflicts}`);
  console.log("");
  console.log(
    `  Dependencies: ${result.dependencies.attribute} attributes, ${result.dependencies.segment} segments, ${result.dependencies.feature} features, ${result.dependencies.group} groups, ${result.dependencies.schema} schemas, ${result.dependencies.target} targets, ${result.dependencies.test} tests`,
  );
  console.log(`  Created:   ${result.files.created.length}`);
  console.log(`  Updated:   ${result.files.updated.length}`);
  console.log(`  Unchanged: ${result.files.unchanged.length}`);
  console.log(`  Conflicts: ${result.conflicts.length}`);
  console.log("");
 
  printFileGroup("Created", result.files.created, CLI_COLOR_GREEN);
  printFileGroup("Updated", result.files.updated, CLI_COLOR_YELLOW);
  Iif (options.showUnchanged === true) {
    printFileGroup("Unchanged", result.files.unchanged, CLI_COLOR_DIM);
  }
  printConflictPreview(result.conflicts);
 
  Iif (result.auditFilePath) {
    console.log(`  Audit: ${colorize(result.auditFilePath, CLI_COLOR_CYAN)}`);
    console.log("");
  }
 
  console.log(CLI_FORMAT_GREEN, result.apply ? "Promotion applied" : "Promotion preview complete");
  console.log(CLI_FORMAT_BOLD, `Time: ${prettyDuration(result.duration)}`);
}
 
export const promotePlugin: Plugin = {
  command: "promote",
  handler: async ({ projectConfig, datasource, parsed }) => {
    const result = await promoteProjectSets(projectConfig, datasource, {
      from: parsed.from,
      to: parsed.to,
      includeFeatures: parsed.includeFeatures,
      excludeFeatures: parsed.excludeFeatures,
      target: parsed.target,
      tag: parsed.tag,
      conflicts: parsed.conflicts,
      allowEmpty: parsed.allowEmpty === true || parsed.allowEmpty === "true",
      apply: parsed.apply === true || parsed.apply === "true",
      audit: parsed.audit,
    });
 
    printPromoteResult(result, {
      showUnchanged: parsed.showUnchanged === true || parsed.showUnchanged === "true",
    });
  },
  examples: [
    {
      command: "promote --from=dev --to=staging",
      description: "preview definitions that can be promoted from one set to another",
    },
    {
      command: "promote --from=dev --to=staging --target=web",
      description: "preview the target and every definition needed to build its datafile",
    },
    {
      command: "promote --from=dev --to=staging --tag=web",
      description: "preview definitions affecting features with a tag",
    },
    {
      command: 'promote --from=dev --to=staging --includeFeatures="checkout*"',
      description: "preview definitions affecting matching features",
    },
    {
      command: "promote --from=dev --to=staging --conflicts=fail",
      description: "fail instead of overwriting conflicting destination fields",
    },
    {
      command: "promote --from=dev --to=staging --apply",
      description: "apply a promotion and write destination files",
    },
    {
      command: "promote --from=dev --to=staging --apply --audit=markdown",
      description: "write a promotion audit file",
    },
    {
      command: "promote --from=dev --to=staging --showUnchanged",
      description: "preview a promotion and include unchanged entries",
    },
  ],
};