@featurevisor/core 3.11.0 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (292) hide show
  1. package/README.md +20 -2
  2. package/lib/assess-distribution/index.js +9 -3
  3. package/lib/assess-distribution/index.js.map +1 -1
  4. package/lib/benchmark/index.d.ts +1 -1
  5. package/lib/benchmark/index.js +18 -11
  6. package/lib/benchmark/index.js.map +1 -1
  7. package/lib/builder/applyContextToConditions.d.ts +5 -4
  8. package/lib/builder/applyContextToConditions.js +84 -89
  9. package/lib/builder/applyContextToConditions.js.map +1 -1
  10. package/lib/builder/applyContextToDatafile.d.ts +2 -2
  11. package/lib/builder/applyContextToDatafile.js +45 -149
  12. package/lib/builder/applyContextToDatafile.js.map +1 -1
  13. package/lib/builder/applyContextToSegments.d.ts +6 -4
  14. package/lib/builder/applyContextToSegments.js +9 -98
  15. package/lib/builder/applyContextToSegments.js.map +1 -1
  16. package/lib/builder/buildDatafile.d.ts +15 -6
  17. package/lib/builder/buildDatafile.js +320 -220
  18. package/lib/builder/buildDatafile.js.map +1 -1
  19. package/lib/builder/buildProject.d.ts +2 -1
  20. package/lib/builder/buildProject.js +36 -37
  21. package/lib/builder/buildProject.js.map +1 -1
  22. package/lib/builder/buildRuntimeDatafiles.js +2 -0
  23. package/lib/builder/buildRuntimeDatafiles.js.map +1 -1
  24. package/lib/builder/environments.d.ts +3 -0
  25. package/lib/builder/environments.js +26 -0
  26. package/lib/builder/environments.js.map +1 -0
  27. package/lib/builder/hashes.d.ts +5 -5
  28. package/lib/builder/hashes.js +82 -100
  29. package/lib/builder/hashes.js.map +1 -1
  30. package/lib/builder/inflate.d.ts +7 -0
  31. package/lib/builder/inflate.js +26 -0
  32. package/lib/builder/inflate.js.map +1 -0
  33. package/lib/builder/mutateVariables.d.ts +6 -2
  34. package/lib/builder/mutateVariables.js +26 -18
  35. package/lib/builder/mutateVariables.js.map +1 -1
  36. package/lib/builder/mutationEntries.d.ts +5 -0
  37. package/lib/builder/mutationEntries.js +23 -0
  38. package/lib/builder/mutationEntries.js.map +1 -0
  39. package/lib/builder/mutator.d.ts +4 -2
  40. package/lib/builder/mutator.js +20 -209
  41. package/lib/builder/mutator.js.map +1 -1
  42. package/lib/builder/traffic.d.ts +2 -4
  43. package/lib/builder/traffic.js +48 -19
  44. package/lib/builder/traffic.js.map +1 -1
  45. package/lib/builder/variableOverrideProgram.d.ts +9 -0
  46. package/lib/builder/variableOverrideProgram.js +147 -0
  47. package/lib/builder/variableOverrideProgram.js.map +1 -0
  48. package/lib/catalog.d.ts +23 -0
  49. package/lib/catalog.js +117 -0
  50. package/lib/catalog.js.map +1 -0
  51. package/lib/cli/cli.d.ts +2 -0
  52. package/lib/cli/cli.js +38 -13
  53. package/lib/cli/cli.js.map +1 -1
  54. package/lib/cli/options.js +72 -17
  55. package/lib/cli/options.js.map +1 -1
  56. package/lib/cli/plugins.js +11 -3
  57. package/lib/cli/plugins.js.map +1 -1
  58. package/lib/cli/suggestions.d.ts +4 -0
  59. package/lib/cli/suggestions.js +61 -0
  60. package/lib/cli/suggestions.js.map +1 -0
  61. package/lib/config/allowedConditions.d.ts +9 -0
  62. package/lib/config/allowedConditions.js +44 -0
  63. package/lib/config/allowedConditions.js.map +1 -0
  64. package/lib/config/index.d.ts +1 -0
  65. package/lib/config/index.js +1 -0
  66. package/lib/config/index.js.map +1 -1
  67. package/lib/config/projectConfig.d.ts +9 -3
  68. package/lib/config/projectConfig.js +68 -11
  69. package/lib/config/projectConfig.js.map +1 -1
  70. package/lib/config/removedGroups.d.ts +5 -0
  71. package/lib/config/removedGroups.js +62 -0
  72. package/lib/config/removedGroups.js.map +1 -0
  73. package/lib/datasource/adapter.d.ts +10 -1
  74. package/lib/datasource/adapter.js.map +1 -1
  75. package/lib/datasource/attributeNamespaces.d.ts +14 -0
  76. package/lib/datasource/attributeNamespaces.js +70 -0
  77. package/lib/datasource/attributeNamespaces.js.map +1 -0
  78. package/lib/datasource/composition.d.ts +5 -0
  79. package/lib/datasource/composition.js +19 -0
  80. package/lib/datasource/composition.js.map +1 -0
  81. package/lib/datasource/conditions.d.ts +20 -0
  82. package/lib/datasource/conditions.js +113 -0
  83. package/lib/datasource/conditions.js.map +1 -0
  84. package/lib/datasource/datasource.d.ts +18 -12
  85. package/lib/datasource/datasource.js +137 -76
  86. package/lib/datasource/datasource.js.map +1 -1
  87. package/lib/datasource/dependencies.d.ts +52 -0
  88. package/lib/datasource/dependencies.js +347 -0
  89. package/lib/datasource/dependencies.js.map +1 -0
  90. package/lib/datasource/filesystemAdapter.d.ts +31 -1
  91. package/lib/datasource/filesystemAdapter.js +581 -99
  92. package/lib/datasource/filesystemAdapter.js.map +1 -1
  93. package/lib/datasource/index.d.ts +3 -0
  94. package/lib/datasource/index.js +3 -0
  95. package/lib/datasource/index.js.map +1 -1
  96. package/lib/datasource/parseError.d.ts +5 -0
  97. package/lib/datasource/parseError.js +68 -0
  98. package/lib/datasource/parseError.js.map +1 -0
  99. package/lib/datasource/testSpecs.d.ts +4 -0
  100. package/lib/datasource/testSpecs.js +40 -0
  101. package/lib/datasource/testSpecs.js.map +1 -0
  102. package/lib/diff/details.js +31 -0
  103. package/lib/diff/details.js.map +1 -1
  104. package/lib/diff/index.d.ts +1 -1
  105. package/lib/diff/index.js +11 -4
  106. package/lib/diff/index.js.map +1 -1
  107. package/lib/error.d.ts +1 -0
  108. package/lib/error.js +6 -0
  109. package/lib/error.js.map +1 -1
  110. package/lib/evaluate/explain.d.ts +15 -2
  111. package/lib/evaluate/explain.js +273 -79
  112. package/lib/evaluate/explain.js.map +1 -1
  113. package/lib/evaluate/index.js +128 -17
  114. package/lib/evaluate/index.js.map +1 -1
  115. package/lib/evaluate/probeConditions.d.ts +30 -0
  116. package/lib/evaluate/probeConditions.js +165 -0
  117. package/lib/evaluate/probeConditions.js.map +1 -0
  118. package/lib/evaluate/validateExplanation.js +175 -16
  119. package/lib/evaluate/validateExplanation.js.map +1 -1
  120. package/lib/find-duplicate-segments/findDuplicateSegments.js +20 -1
  121. package/lib/find-duplicate-segments/findDuplicateSegments.js.map +1 -1
  122. package/lib/find-usage/index.d.ts +14 -1
  123. package/lib/find-usage/index.js +359 -155
  124. package/lib/find-usage/index.js.map +1 -1
  125. package/lib/generate-code/typescript.js +156 -60
  126. package/lib/generate-code/typescript.js.map +1 -1
  127. package/lib/info/index.js +11 -5
  128. package/lib/info/index.js.map +1 -1
  129. package/lib/init/index.js +234 -28
  130. package/lib/init/index.js.map +1 -1
  131. package/lib/linter/attributeSchema.d.ts +6 -11
  132. package/lib/linter/attributeSchema.js +59 -53
  133. package/lib/linter/attributeSchema.js.map +1 -1
  134. package/lib/linter/comparisonOperators.d.ts +18 -0
  135. package/lib/linter/comparisonOperators.js +82 -0
  136. package/lib/linter/comparisonOperators.js.map +1 -0
  137. package/lib/linter/composedOverrideSchema.d.ts +5 -0
  138. package/lib/linter/composedOverrideSchema.js +243 -0
  139. package/lib/linter/composedOverrideSchema.js.map +1 -0
  140. package/lib/linter/compositionWarnings.d.ts +8 -0
  141. package/lib/linter/compositionWarnings.js +212 -0
  142. package/lib/linter/compositionWarnings.js.map +1 -0
  143. package/lib/linter/conditionKinds.d.ts +12 -0
  144. package/lib/linter/conditionKinds.js +129 -0
  145. package/lib/linter/conditionKinds.js.map +1 -0
  146. package/lib/linter/conditionSchema.d.ts +8 -2
  147. package/lib/linter/conditionSchema.js +253 -52
  148. package/lib/linter/conditionSchema.js.map +1 -1
  149. package/lib/linter/contextWarnings.d.ts +13 -0
  150. package/lib/linter/contextWarnings.js +241 -0
  151. package/lib/linter/contextWarnings.js.map +1 -0
  152. package/lib/linter/definitionReferences.d.ts +39 -0
  153. package/lib/linter/definitionReferences.js +234 -0
  154. package/lib/linter/definitionReferences.js.map +1 -0
  155. package/lib/linter/dependencyDepth.d.ts +14 -0
  156. package/lib/linter/dependencyDepth.js +106 -0
  157. package/lib/linter/dependencyDepth.js.map +1 -0
  158. package/lib/linter/diagnostics.d.ts +129 -0
  159. package/lib/linter/diagnostics.js +84 -0
  160. package/lib/linter/diagnostics.js.map +1 -0
  161. package/lib/linter/featureSchema.d.ts +191 -74
  162. package/lib/linter/featureSchema.js +415 -214
  163. package/lib/linter/featureSchema.js.map +1 -1
  164. package/lib/linter/lintProject.d.ts +4 -1
  165. package/lib/linter/lintProject.js +449 -143
  166. package/lib/linter/lintProject.js.map +1 -1
  167. package/lib/linter/mutationNotation.d.ts +7 -1
  168. package/lib/linter/mutationNotation.js +40 -20
  169. package/lib/linter/mutationNotation.js.map +1 -1
  170. package/lib/linter/mutationOrder.d.ts +6 -0
  171. package/lib/linter/mutationOrder.js +105 -0
  172. package/lib/linter/mutationOrder.js.map +1 -0
  173. package/lib/linter/mutationResultPaths.d.ts +4 -0
  174. package/lib/linter/mutationResultPaths.js +131 -0
  175. package/lib/linter/mutationResultPaths.js.map +1 -0
  176. package/lib/linter/mutationSchema.d.ts +3 -0
  177. package/lib/linter/mutationSchema.js +32 -0
  178. package/lib/linter/mutationSchema.js.map +1 -0
  179. package/lib/linter/printError.d.ts +3 -0
  180. package/lib/linter/printError.js +38 -25
  181. package/lib/linter/printError.js.map +1 -1
  182. package/lib/linter/regexSafety.d.ts +19 -0
  183. package/lib/linter/regexSafety.js +307 -0
  184. package/lib/linter/regexSafety.js.map +1 -0
  185. package/lib/linter/removedConditionFields.d.ts +10 -0
  186. package/lib/linter/removedConditionFields.js +47 -0
  187. package/lib/linter/removedConditionFields.js.map +1 -0
  188. package/lib/linter/requiredFeaturesSchema.d.ts +2 -2
  189. package/lib/linter/requiredFeaturesSchema.js +32 -28
  190. package/lib/linter/requiredFeaturesSchema.js.map +1 -1
  191. package/lib/linter/requiredVariableCost.d.ts +5 -0
  192. package/lib/linter/requiredVariableCost.js +60 -0
  193. package/lib/linter/requiredVariableCost.js.map +1 -0
  194. package/lib/linter/requiredVariablesSchema.d.ts +13 -0
  195. package/lib/linter/requiredVariablesSchema.js +498 -0
  196. package/lib/linter/requiredVariablesSchema.js.map +1 -0
  197. package/lib/linter/reservedNames.d.ts +12 -0
  198. package/lib/linter/reservedNames.js +52 -0
  199. package/lib/linter/reservedNames.js.map +1 -0
  200. package/lib/linter/schema.d.ts +12 -15
  201. package/lib/linter/schema.js +108 -26
  202. package/lib/linter/schema.js.map +1 -1
  203. package/lib/linter/schemaFormats.d.ts +35 -0
  204. package/lib/linter/schemaFormats.js +66 -0
  205. package/lib/linter/schemaFormats.js.map +1 -0
  206. package/lib/linter/segmentSchema.d.ts +11 -1
  207. package/lib/linter/segmentSchema.js +12 -2
  208. package/lib/linter/segmentSchema.js.map +1 -1
  209. package/lib/linter/testSchema.d.ts +394 -2
  210. package/lib/linter/testSchema.js +565 -34
  211. package/lib/linter/testSchema.js.map +1 -1
  212. package/lib/linter/variableSchema.d.ts +60 -43
  213. package/lib/linter/variableSchema.js +459 -60
  214. package/lib/linter/variableSchema.js.map +1 -1
  215. package/lib/linter/zodHelpers.d.ts +8 -1
  216. package/lib/linter/zodHelpers.js +9 -1
  217. package/lib/linter/zodHelpers.js.map +1 -1
  218. package/lib/list/index.js +384 -66
  219. package/lib/list/index.js.map +1 -1
  220. package/lib/list/matrix.d.ts +2 -2
  221. package/lib/list/matrix.js +60 -39
  222. package/lib/list/matrix.js.map +1 -1
  223. package/lib/list/scenarios.d.ts +8 -0
  224. package/lib/list/scenarios.js +84 -0
  225. package/lib/list/scenarios.js.map +1 -0
  226. package/lib/promoter/index.d.ts +1 -1
  227. package/lib/promoter/index.js +469 -210
  228. package/lib/promoter/index.js.map +1 -1
  229. package/lib/sets.js +14 -5
  230. package/lib/sets.js.map +1 -1
  231. package/lib/tester/checks.d.ts +12 -0
  232. package/lib/tester/checks.js +418 -0
  233. package/lib/tester/checks.js.map +1 -0
  234. package/lib/tester/coverage.d.ts +16 -0
  235. package/lib/tester/coverage.js +64 -0
  236. package/lib/tester/coverage.js.map +1 -0
  237. package/lib/tester/datafileKey.d.ts +4 -0
  238. package/lib/tester/datafileKey.js +18 -0
  239. package/lib/tester/datafileKey.js.map +1 -0
  240. package/lib/tester/diagnostics.d.ts +5 -0
  241. package/lib/tester/diagnostics.js +32 -0
  242. package/lib/tester/diagnostics.js.map +1 -0
  243. package/lib/tester/index.d.ts +2 -0
  244. package/lib/tester/printTestResult.d.ts +3 -2
  245. package/lib/tester/printTestResult.js +53 -8
  246. package/lib/tester/printTestResult.js.map +1 -1
  247. package/lib/tester/provenance.d.ts +21 -0
  248. package/lib/tester/provenance.js +98 -0
  249. package/lib/tester/provenance.js.map +1 -0
  250. package/lib/tester/report.d.ts +78 -0
  251. package/lib/tester/report.js +246 -0
  252. package/lib/tester/report.js.map +1 -0
  253. package/lib/tester/segments.d.ts +23 -0
  254. package/lib/tester/segments.js +103 -0
  255. package/lib/tester/segments.js.map +1 -0
  256. package/lib/tester/testFeature.d.ts +2 -0
  257. package/lib/tester/testFeature.js +17 -8
  258. package/lib/tester/testFeature.js.map +1 -1
  259. package/lib/tester/testProject.d.ts +15 -3
  260. package/lib/tester/testProject.js +198 -83
  261. package/lib/tester/testProject.js.map +1 -1
  262. package/lib/tester/testSegment.d.ts +2 -4
  263. package/lib/tester/testSegment.js +89 -7
  264. package/lib/tester/testSegment.js.map +1 -1
  265. package/lib/tester/testVariable.d.ts +2 -2
  266. package/lib/tester/testVariable.js +195 -24
  267. package/lib/tester/testVariable.js.map +1 -1
  268. package/lib/utils/conditionReferences.d.ts +5 -0
  269. package/lib/utils/conditionReferences.js +30 -0
  270. package/lib/utils/conditionReferences.js.map +1 -0
  271. package/lib/utils/extractKeys.d.ts +7 -3
  272. package/lib/utils/extractKeys.js +32 -113
  273. package/lib/utils/extractKeys.js.map +1 -1
  274. package/lib/utils/git.d.ts +7 -2
  275. package/lib/utils/git.js +87 -72
  276. package/lib/utils/git.js.map +1 -1
  277. package/package.json +11 -8
  278. package/lib/builder/getFeatureRanges.d.ts +0 -11
  279. package/lib/builder/getFeatureRanges.js +0 -70
  280. package/lib/builder/getFeatureRanges.js.map +0 -1
  281. package/lib/datasource/requiredFeatures.d.ts +0 -14
  282. package/lib/datasource/requiredFeatures.js +0 -75
  283. package/lib/datasource/requiredFeatures.js.map +0 -1
  284. package/lib/linter/checkCircularDependency.d.ts +0 -3
  285. package/lib/linter/checkCircularDependency.js +0 -8
  286. package/lib/linter/checkCircularDependency.js.map +0 -1
  287. package/lib/linter/checkPercentageExceedingSlot.d.ts +0 -3
  288. package/lib/linter/checkPercentageExceedingSlot.js +0 -45
  289. package/lib/linter/checkPercentageExceedingSlot.js.map +0 -1
  290. package/lib/linter/groupSchema.d.ts +0 -11
  291. package/lib/linter/groupSchema.js +0 -31
  292. package/lib/linter/groupSchema.js.map +0 -1
@@ -41,8 +41,12 @@ const fs = __importStar(require("fs"));
41
41
  const path = __importStar(require("path"));
42
42
  const child_process_1 = require("child_process");
43
43
  const zlib_1 = require("zlib");
44
+ const parsers_1 = require("@featurevisor/parsers");
44
45
  const adapter_1 = require("./adapter");
45
46
  const git_1 = require("../utils/git");
47
+ const testSpecs_1 = require("./testSpecs");
48
+ const parseError_1 = require("./parseError");
49
+ const attributeNamespaces_1 = require("./attributeNamespaces");
46
50
  const cliFormat_1 = require("../tester/cliFormat");
47
51
  function getExistingStateFilePath(projectConfig, environment) {
48
52
  const fileName = environment ? `existing-state-${environment}.json` : `existing-state.json`;
@@ -69,12 +73,9 @@ function getAllEntityFilePathsRecursively(directoryPath, extension) {
69
73
  }
70
74
  return entities;
71
75
  }
72
- function isWithinDirectory(directoryPath, fileDirectoryPath) {
73
- return (fileDirectoryPath === directoryPath || fileDirectoryPath.startsWith(directoryPath + path.sep));
74
- }
75
76
  function getPathSegmentsFromKey(namespaceCharacter, key, entityType) {
76
77
  const pathSegments = namespaceCharacter ? key.split(namespaceCharacter) : [key];
77
- if (entityType === "test" &&
78
+ if ((entityType === "test" || entityType === "scenario") &&
78
79
  pathSegments.length > 1 &&
79
80
  ["spec", "feature", "segment"].includes(pathSegments[pathSegments.length - 1])) {
80
81
  const suffix = pathSegments[pathSegments.length - 1];
@@ -83,20 +84,29 @@ function getPathSegmentsFromKey(namespaceCharacter, key, entityType) {
83
84
  }
84
85
  return pathSegments;
85
86
  }
87
+ /** Coarse filesystems record modification times in whole seconds, some in two. */
88
+ const RACY_FILE_MARGIN_MS = 2000;
89
+ function statIdentity(filePath) {
90
+ try {
91
+ const stat = fs.statSync(filePath);
92
+ return { size: stat.size, mtimeMs: stat.mtimeMs, ino: stat.ino };
93
+ }
94
+ catch {
95
+ return undefined;
96
+ }
97
+ }
86
98
  class FilesystemAdapter extends adapter_1.Adapter {
87
99
  constructor(config, rootDirectoryPath) {
88
100
  super();
89
101
  this.config = config;
90
102
  this.rootDirectoryPath = rootDirectoryPath;
103
+ this.testSpecCache = new Map();
91
104
  this.parser = config.parser;
92
105
  }
93
106
  getEntityDirectoryPath(entityType) {
94
107
  if (entityType === "feature") {
95
108
  return this.config.featuresDirectoryPath;
96
109
  }
97
- else if (entityType === "group") {
98
- return this.config.groupsDirectoryPath;
99
- }
100
110
  else if (entityType === "segment") {
101
111
  return this.config.segmentsDirectoryPath;
102
112
  }
@@ -109,7 +119,7 @@ class FilesystemAdapter extends adapter_1.Adapter {
109
119
  else if (entityType === "target") {
110
120
  return this.config.targetsDirectoryPath;
111
121
  }
112
- else if (entityType === "test") {
122
+ else if (entityType === "test" || entityType === "scenario") {
113
123
  return this.config.testsDirectoryPath;
114
124
  }
115
125
  return this.config.attributesDirectoryPath;
@@ -127,22 +137,198 @@ class FilesystemAdapter extends adapter_1.Adapter {
127
137
  .sort();
128
138
  }
129
139
  getEntityPath(entityType, entityKey) {
140
+ if (entityType === "scenario")
141
+ return this.getScenarioSourcePath(entityKey);
142
+ if (entityType === "test")
143
+ return this.getTestSourcePath(entityKey);
130
144
  const basePath = this.getEntityDirectoryPath(entityType);
145
+ if (entityType === "attribute") {
146
+ (0, attributeNamespaces_1.assertFlatAttributeKeys)([entityKey], basePath, this.config.namespaceCharacter, this.parser.extension);
147
+ }
131
148
  const pathSegments = getPathSegmentsFromKey(this.config.namespaceCharacter, entityKey, entityType);
132
149
  return path.join(basePath, ...pathSegments) + `.${this.parser.extension}`;
133
150
  }
151
+ /** Public test identities omit a terminal .spec, while source files keep their names. */
152
+ scenarioPaths(refresh = false) {
153
+ if (this.scenarioPathIndex && !refresh)
154
+ return this.scenarioPathIndex;
155
+ this.scenarioPathIndex = undefined;
156
+ this.testPathIndex = undefined;
157
+ const directory = this.config.testsDirectoryPath;
158
+ const paths = new Map();
159
+ const testPaths = new Map();
160
+ const filePaths = getAllEntityFilePathsRecursively(directory, this.parser.extension);
161
+ const existingPaths = new Set(filePaths);
162
+ for (const cachedPath of this.testSpecCache.keys()) {
163
+ if (!existingPaths.has(cachedPath))
164
+ this.testSpecCache.delete(cachedPath);
165
+ }
166
+ for (const filePath of filePaths) {
167
+ let scenario = false;
168
+ try {
169
+ scenario = (0, testSpecs_1.isScenarioSpec)(this.readTestSpecFile(filePath, false));
170
+ }
171
+ catch {
172
+ // An unreadable spec remains in the entity test collection for diagnostics.
173
+ }
174
+ const relative = path
175
+ .relative(directory, filePath)
176
+ .slice(0, -(this.parser.extension.length + 1));
177
+ const parts = relative.split(path.sep);
178
+ parts[parts.length - 1] = parts[parts.length - 1].replace(/\.spec$/, "");
179
+ const key = parts.join(this.config.namespaceCharacter);
180
+ const collection = scenario ? paths : testPaths;
181
+ const previous = collection.get(key);
182
+ if (previous) {
183
+ throw new Error(`${scenario ? "Scenario" : "Test"} key collision for "${key}": ${previous} and ${filePath}. Rename one source file.`);
184
+ }
185
+ collection.set(key, filePath);
186
+ }
187
+ for (const [key, scenarioPath] of paths) {
188
+ const testPath = testPaths.get(key);
189
+ if (testPath) {
190
+ throw new Error(`Test identity collision for "${key}": ${testPath} and ${scenarioPath}. Rename one source file.`);
191
+ }
192
+ }
193
+ this.testPathIndex = testPaths;
194
+ this.scenarioPathIndex = paths;
195
+ return paths;
196
+ }
197
+ getTestSourcePath(key) {
198
+ const parts = this.config.namespaceCharacter
199
+ ? key.split(this.config.namespaceCharacter)
200
+ : [key];
201
+ const direct = path.join(this.config.testsDirectoryPath, ...parts) + `.${this.parser.extension}`;
202
+ const withSpec = path.join(this.config.testsDirectoryPath, ...parts.slice(0, -1), `${parts[parts.length - 1]}.spec.${this.parser.extension}`);
203
+ this.scenarioPaths();
204
+ let existing = this.testPathIndex?.get(key);
205
+ let stillEntity = false;
206
+ if (existing && fs.existsSync(existing)) {
207
+ try {
208
+ stillEntity = !(0, testSpecs_1.isScenarioSpec)(this.readTestSpecFile(existing, false));
209
+ }
210
+ catch {
211
+ stillEntity = true;
212
+ }
213
+ }
214
+ if ((existing && !stillEntity) ||
215
+ (direct !== existing && fs.existsSync(direct)) ||
216
+ (withSpec !== existing && fs.existsSync(withSpec))) {
217
+ this.scenarioPaths(true);
218
+ existing = this.testPathIndex?.get(key);
219
+ }
220
+ return existing || withSpec;
221
+ }
222
+ getScenarioSourcePath(key) {
223
+ const parts = this.config.namespaceCharacter
224
+ ? key.split(this.config.namespaceCharacter)
225
+ : [key];
226
+ const direct = path.join(this.config.testsDirectoryPath, ...parts) + `.${this.parser.extension}`;
227
+ const withSpec = path.join(this.config.testsDirectoryPath, ...parts.slice(0, -1), `${parts[parts.length - 1]}.spec.${this.parser.extension}`);
228
+ const isScenarioPath = (filePath) => {
229
+ if (!fs.existsSync(filePath))
230
+ return false;
231
+ try {
232
+ return (0, testSpecs_1.isScenarioSpec)(this.readTestSpecFile(filePath, false));
233
+ }
234
+ catch {
235
+ return false;
236
+ }
237
+ };
238
+ let existing = this.scenarioPaths().get(key);
239
+ if (existing && !isScenarioPath(existing))
240
+ existing = this.scenarioPaths(true).get(key);
241
+ const directMatches = direct !== existing && isScenarioPath(direct);
242
+ const specMatches = withSpec !== existing && isScenarioPath(withSpec);
243
+ if (directMatches ||
244
+ specMatches ||
245
+ (!existing && (fs.existsSync(direct) || fs.existsSync(withSpec)))) {
246
+ existing = this.scenarioPaths(true).get(key);
247
+ }
248
+ return existing || withSpec;
249
+ }
134
250
  async listEntities(entityType) {
251
+ if (entityType === "scenario")
252
+ return Array.from(this.scenarioPaths(true).keys());
253
+ if (entityType === "test") {
254
+ this.scenarioPaths(true);
255
+ return Array.from(this.testPathIndex.keys());
256
+ }
135
257
  const directoryPath = this.getEntityDirectoryPath(entityType);
136
258
  const filePaths = getAllEntityFilePathsRecursively(directoryPath, this.parser.extension);
137
- return (filePaths
138
- // keep only the files with the right extension
139
- .filter((filterPath) => filterPath.endsWith(`.${this.parser.extension}`))
140
- // remove the entity directory path from beginning
141
- .map((filePath) => filePath.replace(directoryPath + path.sep, ""))
142
- // remove the extension from the end
143
- .map((filterPath) => filterPath.replace(`.${this.parser.extension}`, ""))
144
- // take care of windows paths and apply namespace character
145
- .map((filterPath) => filterPath.split(path.sep).join(this.config.namespaceCharacter)));
259
+ if (entityType === "attribute") {
260
+ const keyForPath = (filePath) => path
261
+ .relative(directoryPath, filePath)
262
+ .slice(0, -(this.parser.extension.length + 1))
263
+ .split(path.sep)
264
+ .join(this.config.namespaceCharacter);
265
+ const isNested = (filePath) => path.dirname(path.relative(directoryPath, filePath)) !== ".";
266
+ const invalidFiles = filePaths.filter((filePath) => isNested(filePath) ||
267
+ !(0, attributeNamespaces_1.isFlatAttributeKey)(keyForPath(filePath), this.config.namespaceCharacter));
268
+ if (invalidFiles.length) {
269
+ const invalidPaths = new Set(invalidFiles);
270
+ throw new attributeNamespaces_1.AttributeNamespaceError(invalidFiles.map((filePath) => ({ key: keyForPath(filePath), filePath })), filePaths.filter((filePath) => !invalidPaths.has(filePath)).map(keyForPath));
271
+ }
272
+ }
273
+ return filePaths
274
+ .map((filePath) => path.relative(directoryPath, filePath))
275
+ .map((filePath) => filePath.slice(0, -(this.parser.extension.length + 1)))
276
+ .map((filePath) => filePath.split(path.sep).join(this.config.namespaceCharacter));
277
+ }
278
+ /**
279
+ * Path, size, modification time and inode. An editor's atomic save changes the inode even
280
+ * when size and time match. Only built in parsers qualify: a custom parser may read other
281
+ * files, so its output is not tied to this file alone.
282
+ */
283
+ async getEntityFingerprint(entityType, entityKey) {
284
+ if (!Object.values(parsers_1.parsers).includes(this.parser))
285
+ return undefined;
286
+ try {
287
+ const filePath = this.getEntityPath(entityType, entityKey);
288
+ const stat = await fs.promises.stat(filePath);
289
+ return `${filePath}\0${stat.size}:${stat.mtimeMs}:${stat.ino}`;
290
+ }
291
+ catch {
292
+ return undefined;
293
+ }
294
+ }
295
+ readTestSpecFile(filePath, clone = true) {
296
+ let cached = this.testSpecCache.get(filePath);
297
+ const stat = statIdentity(filePath);
298
+ // Listing and reading specs repeatedly, as watch mode does, skips unchanged files. A file
299
+ // modified shortly before it was read may have changed within the same timestamp, so
300
+ // its contents are compared instead, as Git does for racily clean files.
301
+ const unchanged = cached?.stat &&
302
+ stat &&
303
+ cached.stat.size === stat.size &&
304
+ cached.stat.mtimeMs === stat.mtimeMs &&
305
+ cached.stat.ino === stat.ino &&
306
+ stat.mtimeMs < cached.readAt - RACY_FILE_MARGIN_MS;
307
+ if (!cached || !unchanged) {
308
+ const readAt = Date.now();
309
+ const content = fs.readFileSync(filePath, "utf8");
310
+ if (!cached || cached.content !== content) {
311
+ try {
312
+ cached = {
313
+ content,
314
+ result: { value: this.parseEntityContent(content, filePath) },
315
+ stat,
316
+ readAt,
317
+ };
318
+ }
319
+ catch (error) {
320
+ cached = { content, result: { error }, stat, readAt };
321
+ }
322
+ }
323
+ else {
324
+ cached = { ...cached, stat, readAt };
325
+ }
326
+ this.testSpecCache.set(filePath, cached);
327
+ }
328
+ if ("error" in cached.result)
329
+ throw cached.result.error;
330
+ // Consumers can expand or normalize a spec without mutating the cached authoring value.
331
+ return (clone ? structuredClone(cached.result.value) : cached.result.value);
146
332
  }
147
333
  async entityExists(entityType, entityKey) {
148
334
  const entityPath = this.getEntityPath(entityType, entityKey);
@@ -150,15 +336,40 @@ class FilesystemAdapter extends adapter_1.Adapter {
150
336
  }
151
337
  async readEntity(entityType, entityKey) {
152
338
  const filePath = this.getEntityPath(entityType, entityKey);
339
+ if (entityType === "test" || entityType === "scenario") {
340
+ return this.readTestSpecFile(filePath);
341
+ }
153
342
  const entityContent = fs.readFileSync(filePath, "utf8");
154
- return this.parser.parse(entityContent, filePath);
343
+ return this.parseEntityContent(entityContent, filePath);
344
+ }
345
+ parseEntityContent(content, filePath) {
346
+ try {
347
+ return this.parser.parse(content, filePath);
348
+ }
349
+ catch (error) {
350
+ throw new parseError_1.EntityParseError(filePath, error, this.rootDirectoryPath);
351
+ }
155
352
  }
156
353
  async writeEntity(entityType, entityKey, entity) {
157
354
  const filePath = this.getEntityPath(entityType, entityKey);
355
+ if (entityType === "scenario" || entityType === "test") {
356
+ this.scenarioPaths(true);
357
+ const oppositePath = entityType === "scenario"
358
+ ? this.testPathIndex?.get(entityKey)
359
+ : this.scenarioPathIndex?.get(entityKey);
360
+ if (oppositePath && oppositePath !== filePath) {
361
+ throw new Error(`Test identity collision for "${entityKey}": another spec already uses this key.`);
362
+ }
363
+ }
158
364
  if (!fs.existsSync(path.dirname(filePath))) {
159
365
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
160
366
  }
161
367
  fs.writeFileSync(filePath, this.parser.stringify(entity, filePath));
368
+ this.testSpecCache.delete(filePath);
369
+ if (entityType === "test" || entityType === "scenario") {
370
+ this.scenarioPathIndex = undefined;
371
+ this.testPathIndex = undefined;
372
+ }
162
373
  return entity;
163
374
  }
164
375
  async deleteEntity(entityType, entityKey) {
@@ -167,6 +378,11 @@ class FilesystemAdapter extends adapter_1.Adapter {
167
378
  return;
168
379
  }
169
380
  fs.unlinkSync(filePath);
381
+ this.testSpecCache.delete(filePath);
382
+ if (entityType === "test" || entityType === "scenario") {
383
+ this.scenarioPathIndex = undefined;
384
+ this.testPathIndex = undefined;
385
+ }
170
386
  }
171
387
  /**
172
388
  * State
@@ -178,7 +394,7 @@ class FilesystemAdapter extends adapter_1.Adapter {
178
394
  features: {},
179
395
  };
180
396
  }
181
- return require(filePath);
397
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
182
398
  }
183
399
  async writeState(environment, existingState) {
184
400
  const filePath = getExistingStateFilePath(this.config, environment);
@@ -199,15 +415,17 @@ class FilesystemAdapter extends adapter_1.Adapter {
199
415
  }
200
416
  return "0";
201
417
  }
202
- async writeRevision(revision) {
418
+ async writeRevision(revision, datafilesDir) {
203
419
  const filePath = getRevisionFilePath(this.config);
420
+ const outputDirectory = datafilesDir || this.config.datafilesDirectoryPath;
421
+ fs.mkdirSync(outputDirectory, { recursive: true });
204
422
  // write to state directory
205
423
  if (!fs.existsSync(this.config.stateDirectoryPath)) {
206
424
  fs.mkdirSync(this.config.stateDirectoryPath, { recursive: true });
207
425
  }
208
426
  fs.writeFileSync(filePath, revision);
209
427
  // write to datafiles directory, as part of the build process
210
- fs.writeFileSync(path.join(this.config.datafilesDirectoryPath, this.config.revisionFileName), revision);
428
+ fs.writeFileSync(path.join(outputDirectory, this.config.revisionFileName), revision);
211
429
  }
212
430
  /**
213
431
  * Datafile
@@ -263,11 +481,20 @@ class FilesystemAdapter extends adapter_1.Adapter {
263
481
  * History
264
482
  */
265
483
  async getRawHistory(pathPatterns) {
266
- const gitPaths = pathPatterns.join(" ");
267
- const logCommand = `git log --name-only --pretty=format:"%h|%an|%aI" --relative --no-merges -- ${gitPaths}`;
268
- const fullCommand = `(cd ${this.rootDirectoryPath} && ${logCommand})`;
484
+ const rootDirectoryPath = this.rootDirectoryPath;
269
485
  return new Promise(function (resolve, reject) {
270
- const child = (0, child_process_1.spawn)(fullCommand, { shell: true });
486
+ const child = (0, child_process_1.spawn)("git", [
487
+ "-c",
488
+ "core.quotepath=false",
489
+ "log",
490
+ "--name-only",
491
+ "--no-renames",
492
+ "--pretty=format:%h|%an|%aI",
493
+ "--relative",
494
+ "--no-merges",
495
+ "--",
496
+ ...pathPatterns,
497
+ ], { cwd: rootDirectoryPath });
271
498
  let result = "";
272
499
  child.stdout.on("data", function (data) {
273
500
  result += data.toString();
@@ -275,6 +502,7 @@ class FilesystemAdapter extends adapter_1.Adapter {
275
502
  child.stderr.on("data", function (data) {
276
503
  console.error(data.toString());
277
504
  });
505
+ child.on("error", reject);
278
506
  child.on("close", function (code) {
279
507
  if (code === 0) {
280
508
  resolve(result);
@@ -300,9 +528,6 @@ class FilesystemAdapter extends adapter_1.Adapter {
300
528
  else if (entityType === "feature") {
301
529
  pathPatterns = [this.config.featuresDirectoryPath];
302
530
  }
303
- else if (entityType === "group") {
304
- pathPatterns = [this.config.groupsDirectoryPath];
305
- }
306
531
  else if (entityType === "schema") {
307
532
  pathPatterns = [this.config.schemasDirectoryPath];
308
533
  }
@@ -312,7 +537,7 @@ class FilesystemAdapter extends adapter_1.Adapter {
312
537
  else if (entityType === "target") {
313
538
  pathPatterns = [this.config.targetsDirectoryPath];
314
539
  }
315
- else if (entityType === "test") {
540
+ else if (entityType === "test" || entityType === "scenario") {
316
541
  pathPatterns = [this.config.testsDirectoryPath];
317
542
  }
318
543
  }
@@ -321,7 +546,6 @@ class FilesystemAdapter extends adapter_1.Adapter {
321
546
  this.config.featuresDirectoryPath,
322
547
  this.config.attributesDirectoryPath,
323
548
  this.config.segmentsDirectoryPath,
324
- this.config.groupsDirectoryPath,
325
549
  this.config.schemasDirectoryPath,
326
550
  this.config.variablesDirectoryPath,
327
551
  this.config.targetsDirectoryPath,
@@ -332,98 +556,356 @@ class FilesystemAdapter extends adapter_1.Adapter {
332
556
  }
333
557
  async listHistoryEntries(entityType, entityKey) {
334
558
  const pathPatterns = this.getPathPatterns(entityType, entityKey);
335
- const rawHistory = await this.getRawHistory(pathPatterns);
336
559
  const fullHistory = [];
337
- const blocks = rawHistory.split("\n\n");
338
- for (let i = 0; i < blocks.length; i++) {
339
- const block = blocks[i];
340
- if (block.length === 0) {
341
- continue;
560
+ // Test specs are classified after the log ends, in one batch, rather than with two
561
+ // `git show` processes per changed spec. Their entity slot is held by a placeholder.
562
+ const pendingTests = new Map();
563
+ let entry;
564
+ let field = 0;
565
+ let firstPath = false;
566
+ const finishEntry = () => {
567
+ if (entry && entry.entities.length > 0)
568
+ fullHistory.push(entry);
569
+ entry = undefined;
570
+ field = 0;
571
+ };
572
+ const consume = (token) => {
573
+ if (field === 0) {
574
+ if (!token)
575
+ return;
576
+ entry = { commit: token, author: "", timestamp: "", subject: "", entities: [] };
577
+ field++;
578
+ }
579
+ else if (field === 1) {
580
+ entry.author = token;
581
+ field++;
582
+ }
583
+ else if (field === 2) {
584
+ entry.timestamp = token;
585
+ field++;
342
586
  }
343
- const lines = block.split("\n");
344
- const commitLine = lines[0];
345
- const [commitHash, author, timestamp] = commitLine.split("|");
346
- const entities = [];
347
- const filePathLines = lines.slice(1);
348
- for (let j = 0; j < filePathLines.length; j++) {
349
- const relativePath = filePathLines[j];
350
- const absolutePath = path.join(this.rootDirectoryPath, relativePath);
351
- const fileName = absolutePath.split(path.sep).pop();
352
- const relativeDir = path.dirname(absolutePath);
353
- const extensionWithDot = "." + this.parser.extension;
354
- const key = fileName.replace(extensionWithDot, "");
355
- let type = "attribute";
356
- if (isWithinDirectory(this.config.attributesDirectoryPath, relativeDir)) {
357
- type = "attribute";
587
+ else if (field === 3) {
588
+ entry.subject = token;
589
+ field++;
590
+ firstPath = true;
591
+ }
592
+ else {
593
+ // Git inserts one newline between the header and the first raw filename.
594
+ const relativePath = firstPath && token.startsWith("\n") ? token.slice(1) : token;
595
+ firstPath = false;
596
+ if (!relativePath) {
597
+ finishEntry();
598
+ return;
599
+ }
600
+ const entity = (0, git_1.getHistoryEntity)(relativePath, {
601
+ rootDirectoryPath: this.rootDirectoryPath,
602
+ projectConfig: this.config,
603
+ }, this.config.namespaceCharacter);
604
+ if (!entity)
605
+ return;
606
+ if (entity.type === "test") {
607
+ const placeholder = { type: entity.type, key: (0, testSpecs_1.testSpecKeyFromStorageKey)(entity.key) };
608
+ pendingTests.set(placeholder, {
609
+ commit: entry.commit,
610
+ relativePath,
611
+ key: placeholder.key,
612
+ });
613
+ entry.entities.push(placeholder);
614
+ return;
358
615
  }
359
- else if (isWithinDirectory(this.config.segmentsDirectoryPath, relativeDir)) {
360
- type = "segment";
616
+ if (!entityType || entity.type === entityType)
617
+ entry.entities.push({
618
+ type: entity.type,
619
+ key: (0, testSpecs_1.testSpecKeyFromStorageKey)(entity.key),
620
+ });
621
+ }
622
+ };
623
+ return new Promise((resolve, reject) => {
624
+ const child = (0, child_process_1.spawn)("git", [
625
+ "log",
626
+ "--name-only",
627
+ "--no-renames",
628
+ "-z",
629
+ "--encoding=UTF-8",
630
+ "--pretty=format:%x00%h%x00%an%x00%aI%x00%s%x00",
631
+ "--relative",
632
+ "--no-merges",
633
+ "--",
634
+ ...pathPatterns,
635
+ ], { cwd: this.rootDirectoryPath, env: { ...process.env, LC_ALL: "C" } });
636
+ // Retain only the unfinished token, not the full log or a commit's file list.
637
+ let fragments = [];
638
+ let diagnostic = "";
639
+ let failed = false;
640
+ const fail = (error) => {
641
+ if (failed)
642
+ return;
643
+ failed = true;
644
+ child.kill();
645
+ reject(error);
646
+ };
647
+ child.stdout.setEncoding("utf8");
648
+ child.stdout.on("data", (chunk) => {
649
+ if (failed)
650
+ return;
651
+ try {
652
+ let start = 0;
653
+ let end;
654
+ while ((end = chunk.indexOf("\0", start)) !== -1) {
655
+ const part = chunk.slice(start, end);
656
+ consume(fragments.length ? fragments.join("") + part : part);
657
+ fragments = [];
658
+ start = end + 1;
659
+ }
660
+ if (start < chunk.length)
661
+ fragments.push(chunk.slice(start));
361
662
  }
362
- else if (isWithinDirectory(this.config.featuresDirectoryPath, relativeDir)) {
363
- type = "feature";
663
+ catch (error) {
664
+ fail(error);
364
665
  }
365
- else if (isWithinDirectory(this.config.groupsDirectoryPath, relativeDir)) {
366
- type = "group";
666
+ });
667
+ child.stderr.on("data", (data) => {
668
+ diagnostic += data.toString();
669
+ // Bound diagnostics too; oversized messages must never qualify as empty history.
670
+ if (diagnostic.length > 8192) {
671
+ console.error(diagnostic);
672
+ diagnostic = "Git diagnostics exceeded the history limit";
367
673
  }
368
- else if (isWithinDirectory(this.config.schemasDirectoryPath, relativeDir)) {
369
- type = "schema";
674
+ });
675
+ child.stdout.on("error", fail);
676
+ child.stderr.on("error", fail);
677
+ child.on("error", (error) => {
678
+ if (error.code === "ENOENT" && fs.existsSync(this.rootDirectoryPath || ".")) {
679
+ failed = true;
680
+ resolve([]);
370
681
  }
371
- else if (isWithinDirectory(this.config.variablesDirectoryPath, relativeDir)) {
372
- type = "variable";
682
+ else
683
+ fail(error);
684
+ });
685
+ child.on("close", (code) => {
686
+ if (failed)
687
+ return;
688
+ if (code !== 0) {
689
+ if (code === 128 &&
690
+ (/^fatal: not a git repository \(or any of the parent directories\): \.git\s*$/.test(diagnostic) ||
691
+ /^fatal: your current branch '[^'\n]+' does not have any commits yet\s*$/.test(diagnostic))) {
692
+ resolve([]);
693
+ return;
694
+ }
695
+ if (diagnostic)
696
+ console.error(diagnostic);
697
+ reject(code);
698
+ return;
373
699
  }
374
- else if (isWithinDirectory(this.config.targetsDirectoryPath, relativeDir)) {
375
- type = "target";
700
+ if (diagnostic)
701
+ console.error(diagnostic);
702
+ try {
703
+ if (fragments.length)
704
+ consume(fragments.join(""));
705
+ finishEntry();
376
706
  }
377
- else if (isWithinDirectory(this.config.testsDirectoryPath, relativeDir)) {
378
- type = "test";
707
+ catch (error) {
708
+ fail(error);
709
+ return;
379
710
  }
380
- else {
381
- continue;
711
+ this.resolveHistoricalTests(fullHistory, pendingTests, entityType).then(resolve, reject);
712
+ });
713
+ });
714
+ }
715
+ /**
716
+ * Replace test placeholders with "test" and/or "scenario" entities. Both kinds are included
717
+ * when a spec changes ownership, and the parent revision covers deletions.
718
+ */
719
+ async resolveHistoricalTests(history, pending, entityType) {
720
+ if (pending.size === 0)
721
+ return history;
722
+ const requests = [];
723
+ for (const { commit, relativePath } of pending.values()) {
724
+ requests.push({ revision: commit, relativePath }, { revision: `${commit}^`, relativePath });
725
+ }
726
+ const kinds = await this.classifyHistoricalTestSpecs(requests);
727
+ const resolved = [];
728
+ for (const historyEntry of history) {
729
+ historyEntry.entities = historyEntry.entities.flatMap((entity) => {
730
+ const item = pending.get(entity);
731
+ if (!item)
732
+ return [entity];
733
+ const types = new Set();
734
+ for (const revision of [item.commit, `${item.commit}^`]) {
735
+ const kind = kinds.get(`${revision}:${item.relativePath}`);
736
+ if (kind)
737
+ types.add(kind);
382
738
  }
383
- if (type === "feature" || type === "target" || type === "variable") {
384
- const entityDirectoryPath = type === "feature"
385
- ? this.config.featuresDirectoryPath
386
- : type === "target"
387
- ? this.config.targetsDirectoryPath
388
- : this.config.variablesDirectoryPath;
389
- const baseRelativePath = absolutePath
390
- .replace(entityDirectoryPath + path.sep, "")
391
- .replace(extensionWithDot, "")
392
- .split(path.sep)
393
- .join(this.config.namespaceCharacter);
394
- entities.push({
395
- type,
396
- key: baseRelativePath,
739
+ if (types.size === 0)
740
+ types.add("test");
741
+ return [...types]
742
+ .filter((type) => !entityType || type === entityType)
743
+ .map((type) => ({ type, key: entity.key }));
744
+ });
745
+ if (historyEntry.entities.length > 0)
746
+ resolved.push(historyEntry);
747
+ }
748
+ return resolved;
749
+ }
750
+ /** Classify a historical spec the same way as before: a parse failure still counts as a test. */
751
+ classifyHistoricalContent(content, relativePath) {
752
+ try {
753
+ const value = this.parser.parse(content, path.join(this.rootDirectoryPath, relativePath));
754
+ return (0, testSpecs_1.isScenarioSpec)(value) ? "scenario" : "test";
755
+ }
756
+ catch {
757
+ return "test";
758
+ }
759
+ }
760
+ classifyHistoricalTestSpecFallback(revision, relativePath) {
761
+ try {
762
+ const value = this.readHistoricalTestSpec(revision, relativePath);
763
+ if (typeof value === "undefined")
764
+ return undefined;
765
+ return (0, testSpecs_1.isScenarioSpec)(value) ? "scenario" : "test";
766
+ }
767
+ catch {
768
+ return "test";
769
+ }
770
+ }
771
+ /**
772
+ * Read many `revision:path` specs through one `git cat-file --batch` process. Answers arrive
773
+ * in request order. Identical blobs at the same path are classified once. Any request the
774
+ * batch cannot answer exactly falls back to an individual `git show`.
775
+ */
776
+ async classifyHistoricalTestSpecs(requests) {
777
+ const kinds = new Map();
778
+ const unique = [
779
+ ...new Map(requests.map((request) => [`${request.revision}:${request.relativePath}`, request])).values(),
780
+ ];
781
+ // cat-file reads one object name per line, so line breaks in a path cannot be batched.
782
+ const batchable = unique.filter((request) => !/[\r\n]/.test(request.relativePath));
783
+ const fallback = (request) => kinds.set(`${request.revision}:${request.relativePath}`, this.classifyHistoricalTestSpecFallback(request.revision, request.relativePath));
784
+ if (batchable.length > 0) {
785
+ const answered = await new Promise((resolve) => {
786
+ const byBlob = new Map();
787
+ let index = 0;
788
+ let pendingBytes = [];
789
+ let pendingLength = 0;
790
+ let header;
791
+ let settled = false;
792
+ const finish = () => {
793
+ if (settled)
794
+ return;
795
+ settled = true;
796
+ resolve(index);
797
+ };
798
+ let child;
799
+ try {
800
+ child = (0, child_process_1.spawn)("git", ["cat-file", "--batch"], {
801
+ cwd: this.rootDirectoryPath,
802
+ stdio: ["pipe", "pipe", "ignore"],
397
803
  });
398
- continue;
399
804
  }
400
- entities.push({
401
- type,
402
- key,
805
+ catch {
806
+ finish();
807
+ return;
808
+ }
809
+ // Without both pipes the batch cannot run. Every request falls back to `git show`.
810
+ if (!child.stdin || !child.stdout) {
811
+ finish();
812
+ return;
813
+ }
814
+ const stdin = child.stdin;
815
+ const take = (length) => {
816
+ const joined = pendingBytes.length === 1 ? pendingBytes[0] : Buffer.concat(pendingBytes);
817
+ pendingBytes = length < joined.length ? [joined.subarray(length)] : [];
818
+ pendingLength = joined.length - length;
819
+ return joined.subarray(0, length);
820
+ };
821
+ child.stdout.on("data", (chunk) => {
822
+ pendingBytes.push(chunk);
823
+ pendingLength += chunk.length;
824
+ while (index < batchable.length) {
825
+ if (!header) {
826
+ const joined = pendingBytes.length === 1 ? pendingBytes[0] : Buffer.concat(pendingBytes);
827
+ pendingBytes = [joined];
828
+ const newline = joined.indexOf(10);
829
+ if (newline === -1)
830
+ return;
831
+ const line = take(newline + 1)
832
+ .subarray(0, newline)
833
+ .toString("utf8");
834
+ const match = /^([0-9a-f]{40,64}) (\w+) (\d+)$/.exec(line);
835
+ if (!match) {
836
+ // "missing" or "ambiguous": `git show` would fail for these too.
837
+ const request = batchable[index++];
838
+ kinds.set(`${request.revision}:${request.relativePath}`, undefined);
839
+ continue;
840
+ }
841
+ header = { oid: match[1], type: match[2], size: Number(match[3]) };
842
+ }
843
+ if (pendingLength < header.size + 1)
844
+ return;
845
+ const content = take(header.size + 1).subarray(0, header.size);
846
+ const request = batchable[index++];
847
+ const id = `${request.revision}:${request.relativePath}`;
848
+ if (header.type !== "blob") {
849
+ fallback(request);
850
+ }
851
+ else {
852
+ const blobKey = `${header.oid}:${request.relativePath}`;
853
+ let kind = byBlob.get(blobKey);
854
+ if (!kind) {
855
+ kind = this.classifyHistoricalContent(content.toString("utf8"), request.relativePath);
856
+ byBlob.set(blobKey, kind);
857
+ }
858
+ kinds.set(id, kind);
859
+ }
860
+ header = undefined;
861
+ }
403
862
  });
404
- }
405
- if (entities.length === 0) {
406
- continue;
407
- }
408
- fullHistory.push({
409
- commit: commitHash,
410
- author,
411
- timestamp,
412
- entities,
863
+ child.on("error", finish);
864
+ child.on("close", finish);
865
+ stdin.on("error", finish);
866
+ stdin.end(batchable.map((request) => `${request.revision}:./${request.relativePath}`).join("\n") +
867
+ "\n");
413
868
  });
869
+ // Anything the batch did not answer, for example after a Git failure, is read individually.
870
+ batchable.slice(answered).forEach(fallback);
414
871
  }
415
- return fullHistory;
872
+ unique.filter((request) => /[\r\n]/.test(request.relativePath)).forEach(fallback);
873
+ return kinds;
874
+ }
875
+ readHistoricalTestSpec(revision, relativePath) {
876
+ let content;
877
+ try {
878
+ content = (0, child_process_1.execFileSync)("git", ["show", `${revision}:./${relativePath}`], {
879
+ cwd: this.rootDirectoryPath,
880
+ encoding: "utf8",
881
+ stdio: ["ignore", "pipe", "pipe"],
882
+ });
883
+ }
884
+ catch {
885
+ return undefined;
886
+ }
887
+ return this.parser.parse(content, path.join(this.rootDirectoryPath, relativePath));
416
888
  }
417
889
  async readCommit(commitHash, entityType, entityKey) {
418
890
  const pathPatterns = this.getPathPatterns(entityType, entityKey);
419
- const gitPaths = pathPatterns.join(" ");
420
- const logCommand = `git show ${commitHash} --relative -- ${gitPaths}`;
421
- const fullCommand = `(cd ${this.rootDirectoryPath} && ${logCommand})`;
422
- const gitShowOutput = (0, child_process_1.execSync)(fullCommand, { encoding: "utf8" }).toString();
891
+ const gitShowOutput = (0, child_process_1.execFileSync)("git", [
892
+ "-c",
893
+ "core.quotepath=false",
894
+ "show",
895
+ "--no-renames",
896
+ "--relative",
897
+ commitHash,
898
+ "--",
899
+ ...pathPatterns,
900
+ ], { cwd: this.rootDirectoryPath, encoding: "utf8" });
423
901
  const commit = (0, git_1.getCommit)(gitShowOutput, {
424
902
  rootDirectoryPath: this.rootDirectoryPath,
425
903
  projectConfig: this.config,
904
+ readTestSpec: (revision, filePath) => this.readHistoricalTestSpec(revision, filePath),
426
905
  });
906
+ if (entityType) {
907
+ commit.entities = commit.entities.filter((entity) => entity.type === entityType);
908
+ }
427
909
  return commit;
428
910
  }
429
911
  }