dd-trace 5.135.0 → 5.136.0

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 (250) hide show
  1. package/ci/init.js +2 -22
  2. package/ext/exporters.js +0 -1
  3. package/index.d.ts +105 -5
  4. package/initialize.mjs +5 -2
  5. package/lambda.d.ts +39 -0
  6. package/lambda.js +3 -0
  7. package/package.json +11 -9
  8. package/packages/datadog-esbuild/index.js +8 -55
  9. package/packages/datadog-instrumentations/src/aws-lambda.js +88 -0
  10. package/packages/datadog-instrumentations/src/cucumber.js +5 -2
  11. package/packages/datadog-instrumentations/src/elevenlabs/activity.js +114 -0
  12. package/packages/datadog-instrumentations/src/elevenlabs/audio.js +104 -0
  13. package/packages/datadog-instrumentations/src/elevenlabs/index.js +288 -0
  14. package/packages/datadog-instrumentations/src/elevenlabs/session.js +444 -0
  15. package/packages/datadog-instrumentations/src/graphql.js +20 -17
  16. package/packages/{datadog-esbuild/src/utils.js → datadog-instrumentations/src/helpers/bundler-esm-exports.js} +282 -40
  17. package/packages/datadog-instrumentations/src/helpers/bundler-transform.js +573 -0
  18. package/packages/datadog-instrumentations/src/helpers/bundler-utils.js +104 -0
  19. package/packages/datadog-instrumentations/src/helpers/hook.js +29 -1
  20. package/packages/datadog-instrumentations/src/helpers/hooks.js +3 -7
  21. package/packages/datadog-instrumentations/src/helpers/lambda-handler.js +189 -0
  22. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +2 -0
  23. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +18 -1
  24. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/async-mutex.js +41 -0
  25. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/elevenlabs.js +25 -0
  26. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql.js +0 -36
  27. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/next.js +40 -0
  28. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/openai-agents-realtime.js +23 -0
  29. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/trpc.js +148 -0
  30. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +50 -0
  31. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +17 -3
  32. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +59 -2
  33. package/packages/datadog-instrumentations/src/ioredis.js +101 -3
  34. package/packages/datadog-instrumentations/src/next.js +19 -6
  35. package/packages/datadog-instrumentations/src/openai-agents-realtime.js +149 -0
  36. package/packages/datadog-instrumentations/src/openai-realtime/audio-accumulator.js +27 -0
  37. package/packages/datadog-instrumentations/src/openai-realtime/index.js +17 -6
  38. package/packages/datadog-instrumentations/src/openai-realtime/server-playback.js +887 -0
  39. package/packages/datadog-instrumentations/src/openai-realtime/session.js +150 -25
  40. package/packages/datadog-instrumentations/src/openai-realtime/turns.js +29 -2
  41. package/packages/datadog-instrumentations/src/otel-sdk-trace.js +11 -9
  42. package/packages/datadog-instrumentations/src/webdriverio.js +12 -12
  43. package/packages/datadog-plugin-async-mutex/src/index.js +50 -0
  44. package/packages/datadog-plugin-aws-lambda/src/index.js +106 -0
  45. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +22 -11
  46. package/packages/datadog-plugin-elevenlabs/src/index.js +69 -0
  47. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +10 -7
  48. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +19 -52
  49. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +4 -2
  50. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-request-context.js +25 -4
  51. package/packages/datadog-plugin-http/src/client.js +32 -9
  52. package/packages/datadog-plugin-http2/src/client.js +38 -13
  53. package/packages/datadog-plugin-next/src/index.js +112 -14
  54. package/packages/datadog-plugin-prisma/src/datadog-tracing-helper.js +5 -3
  55. package/packages/datadog-plugin-trpc/src/index.js +15 -0
  56. package/packages/datadog-plugin-trpc/src/procedure.js +48 -0
  57. package/packages/datadog-plugin-trpc/src/request.js +81 -0
  58. package/packages/datadog-plugin-undici/src/index.js +22 -7
  59. package/packages/datadog-turbopack/index.js +4 -28
  60. package/packages/datadog-turbopack/src/loader.js +14 -452
  61. package/packages/datadog-webpack/index.js +3 -55
  62. package/packages/dd-trace/src/aiguard/evaluation.js +62 -1
  63. package/packages/dd-trace/src/aiguard/sdk.js +8 -2
  64. package/packages/dd-trace/src/aiguard/tags.js +2 -0
  65. package/packages/dd-trace/src/appsec/blocking/index.js +4 -0
  66. package/packages/dd-trace/src/appsec/graphql.js +91 -6
  67. package/packages/dd-trace/src/appsec/recommended.json +1287 -90
  68. package/packages/dd-trace/src/before-exit.js +32 -0
  69. package/packages/dd-trace/src/bootstrap.js +5 -3
  70. package/packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js +15 -2
  71. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +12 -34
  72. package/packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js +41 -13
  73. package/packages/dd-trace/src/ci-visibility/exporters/request.js +2 -3
  74. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +1 -2
  75. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +1 -1
  76. package/packages/dd-trace/src/ci-visibility/telemetry.js +6 -0
  77. package/packages/dd-trace/src/ci-visibility/test-management/get-test-management-tests.js +1 -1
  78. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache-schema.js +9 -134
  79. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache.js +11 -156
  80. package/packages/dd-trace/src/config/config-types.d.ts +3 -0
  81. package/packages/dd-trace/src/config/defaults.js +5 -0
  82. package/packages/dd-trace/src/config/generated-config-types.d.ts +42 -2
  83. package/packages/dd-trace/src/config/index.js +17 -5
  84. package/packages/dd-trace/src/config/parsers.js +9 -0
  85. package/packages/dd-trace/src/config/supported-configurations.json +158 -4
  86. package/packages/dd-trace/src/constants.js +1 -0
  87. package/packages/dd-trace/src/debugger/pause-duration-histogram.js +2 -1
  88. package/packages/dd-trace/src/exporter.js +0 -11
  89. package/packages/dd-trace/src/exporters/common/request.js +81 -48
  90. package/packages/dd-trace/src/exporters/common/retry.js +12 -7
  91. package/packages/dd-trace/src/exporters/common/url.js +1 -1
  92. package/packages/dd-trace/src/id.js +1 -1
  93. package/packages/dd-trace/src/lambda/facade.js +74 -0
  94. package/packages/dd-trace/src/lambda/handler.js +3 -41
  95. package/packages/dd-trace/src/lambda/index.js +38 -15
  96. package/packages/dd-trace/src/lambda/runtime/patch.js +19 -3
  97. package/packages/dd-trace/src/lambda/wrap.js +44 -0
  98. package/packages/dd-trace/src/llmobs/constants/tags.js +2 -0
  99. package/packages/dd-trace/src/llmobs/experiments/experiment.js +10 -5
  100. package/packages/dd-trace/src/llmobs/plugins/elevenlabs.js +96 -0
  101. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +19 -6
  102. package/packages/dd-trace/src/llmobs/plugins/openai/realtime.js +38 -11
  103. package/packages/dd-trace/src/llmobs/plugins/vertexai.js +10 -2
  104. package/packages/dd-trace/src/llmobs/sdk.js +19 -0
  105. package/packages/dd-trace/src/llmobs/span_processor.js +9 -0
  106. package/packages/dd-trace/src/llmobs/tagger.js +22 -0
  107. package/packages/dd-trace/src/log/channels.js +4 -0
  108. package/packages/dd-trace/src/log/writer.js +6 -1
  109. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +4 -0
  110. package/packages/dd-trace/src/openfeature/configuration_source.js +35 -27
  111. package/packages/dd-trace/src/openfeature/flag-selection.js +152 -0
  112. package/packages/dd-trace/src/openfeature/flagging_provider.js +19 -1
  113. package/packages/dd-trace/src/openfeature/writers/base.js +1 -3
  114. package/packages/dd-trace/src/opentelemetry/logs/index.js +11 -0
  115. package/packages/dd-trace/src/opentelemetry/logs/otlp_http_log_exporter.js +1 -1
  116. package/packages/dd-trace/src/opentelemetry/metrics/index.js +7 -1
  117. package/packages/dd-trace/src/opentelemetry/metrics/otlp_http_metric_exporter.js +1 -1
  118. package/packages/dd-trace/src/opentelemetry/metrics/otlp_span_stats_exporter.js +4 -1
  119. package/packages/dd-trace/src/opentelemetry/otlp/otlp_http_exporter_base.js +19 -1
  120. package/packages/dd-trace/src/opentelemetry/span-ending-hook.js +5 -1
  121. package/packages/dd-trace/src/opentelemetry/span-helpers.js +6 -1
  122. package/packages/dd-trace/src/opentelemetry/span.js +2 -2
  123. package/packages/dd-trace/src/opentelemetry/startup-config.js +174 -0
  124. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +1 -1
  125. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +7 -1
  126. package/packages/dd-trace/src/opentracing/propagation/tracestate.js +77 -23
  127. package/packages/dd-trace/src/opentracing/tracer.js +24 -0
  128. package/packages/dd-trace/src/otel-thread-ctx.js +28 -31
  129. package/packages/dd-trace/src/plugin_manager.js +34 -7
  130. package/packages/dd-trace/src/plugins/ci_plugin.js +41 -10
  131. package/packages/dd-trace/src/plugins/index.js +6 -0
  132. package/packages/dd-trace/src/plugins/plugin.js +4 -2
  133. package/packages/dd-trace/src/plugins/tracing.js +1 -1
  134. package/packages/dd-trace/src/plugins/util/ci.js +18 -1
  135. package/packages/dd-trace/src/plugins/util/git-cache.js +4 -4
  136. package/packages/dd-trace/src/plugins/util/git.js +263 -82
  137. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +75 -46
  138. package/packages/dd-trace/src/plugins/util/inferred_proxy.js +12 -4
  139. package/packages/dd-trace/src/plugins/util/status-validator.js +23 -10
  140. package/packages/dd-trace/src/plugins/util/tags.js +6 -0
  141. package/packages/dd-trace/src/plugins/util/test.js +64 -39
  142. package/packages/dd-trace/src/plugins/util/url.js +10 -2
  143. package/packages/dd-trace/src/plugins/util/user-provided-git.js +2 -2
  144. package/packages/dd-trace/src/plugins/util/web.js +65 -10
  145. package/packages/dd-trace/src/profiling/webspan-utils.js +6 -5
  146. package/packages/dd-trace/src/proxy.js +33 -53
  147. package/packages/dd-trace/src/span_processor.js +20 -0
  148. package/packages/dd-trace/src/startup-log.js +8 -6
  149. package/packages/dd-trace/src/telemetry/metrics.js +2 -1
  150. package/packages/dd-trace/src/tracer.js +0 -2
  151. package/packages/dd-trace/src/web-tags-cache.js +8 -9
  152. package/register.js +2 -1
  153. package/vendor/dist/@apm-js-collab/code-transformer/LICENSE +489 -0
  154. package/vendor/dist/@datadog/flagging-core/LICENSE +221 -0
  155. package/vendor/dist/@datadog/flagging-core/index.js +1 -0
  156. package/vendor/dist/@datadog/openfeature-node-server/LICENSE +21 -1
  157. package/vendor/dist/@datadog/openfeature-node-server/rules-based/LICENSE +3 -1
  158. package/vendor/dist/@datadog/sketches-js/LICENSE +263 -0
  159. package/vendor/dist/@datadog/source-map/LICENSE +1 -0
  160. package/vendor/dist/@isaacs/ttlcache/LICENSE +13 -0
  161. package/vendor/dist/@opentelemetry/core/LICENSE +209 -1
  162. package/vendor/dist/crypto-randomuuid/LICENSE +3 -0
  163. package/vendor/dist/escape-string-regexp/LICENSE +13 -0
  164. package/vendor/dist/esquery/LICENSE +2 -0
  165. package/vendor/dist/https-proxy-agent/LICENSE +80 -1
  166. package/vendor/dist/istanbul-lib-coverage/LICENSE +2 -0
  167. package/vendor/dist/jest-docblock/LICENSE +16 -0
  168. package/vendor/dist/jsonpath-plus/LICENSE +13 -0
  169. package/vendor/dist/limiter/LICENSE +2 -0
  170. package/vendor/dist/lodash.sortby/LICENSE +2 -0
  171. package/vendor/dist/lru-cache/LICENSE +13 -0
  172. package/vendor/dist/meriyah/LICENSE +13 -0
  173. package/vendor/dist/module-details-from-path/LICENSE +2 -0
  174. package/vendor/dist/mutexify/promise/LICENSE +28 -0
  175. package/vendor/dist/pprof-format/LICENSE +13 -0
  176. package/vendor/dist/pprof-format/index.js +1 -1
  177. package/vendor/dist/protobufjs/LICENSE +219 -0
  178. package/vendor/dist/protobufjs/minimal/LICENSE +219 -0
  179. package/vendor/dist/proxy-from-env/LICENSE +13 -0
  180. package/vendor/dist/retry/LICENSE +2 -0
  181. package/vendor/dist/rfdc/LICENSE +2 -0
  182. package/vendor/dist/semifies/LICENSE +3 -1
  183. package/vendor/dist/shell-quote/LICENSE +3 -1
  184. package/vendor/dist/source-map/LICENSE +1 -0
  185. package/vendor/dist/source-map/lib/util/LICENSE +1 -0
  186. package/vendor/dist/tlhunter-sorted-set/LICENSE +2 -0
  187. package/vendor/dist/ttl-set/LICENSE +28 -0
  188. package/ci/diagnose.js +0 -2215
  189. package/ci/runbook.md +0 -299
  190. package/ci/test-optimization-validation/approval-artifacts.js +0 -175
  191. package/ci/test-optimization-validation/approval.js +0 -386
  192. package/ci/test-optimization-validation/artifact-id.js +0 -18
  193. package/ci/test-optimization-validation/blocker-category.js +0 -24
  194. package/ci/test-optimization-validation/bounded-json.js +0 -120
  195. package/ci/test-optimization-validation/ci-command-candidate.js +0 -77
  196. package/ci/test-optimization-validation/ci-discovery.js +0 -192
  197. package/ci/test-optimization-validation/ci-package-scripts.js +0 -169
  198. package/ci/test-optimization-validation/ci-remediation.js +0 -283
  199. package/ci/test-optimization-validation/cli.js +0 -954
  200. package/ci/test-optimization-validation/command-blocker.js +0 -377
  201. package/ci/test-optimization-validation/command-output-policy.js +0 -188
  202. package/ci/test-optimization-validation/command-runner.js +0 -649
  203. package/ci/test-optimization-validation/environment.js +0 -88
  204. package/ci/test-optimization-validation/executable-approval.js +0 -47
  205. package/ci/test-optimization-validation/executable.js +0 -244
  206. package/ci/test-optimization-validation/execution-lock.js +0 -70
  207. package/ci/test-optimization-validation/framework-adapters/cucumber-validation.json +0 -3
  208. package/ci/test-optimization-validation/framework-adapters/cucumber.js +0 -767
  209. package/ci/test-optimization-validation/framework-adapters/cypress.js +0 -99
  210. package/ci/test-optimization-validation/framework-adapters/playwright.js +0 -175
  211. package/ci/test-optimization-validation/framework-adapters/vitest.js +0 -513
  212. package/ci/test-optimization-validation/generated-file-policy.js +0 -63
  213. package/ci/test-optimization-validation/generated-files.js +0 -425
  214. package/ci/test-optimization-validation/generated-test-contract.js +0 -284
  215. package/ci/test-optimization-validation/generated-verifier.js +0 -235
  216. package/ci/test-optimization-validation/literal-environment.js +0 -56
  217. package/ci/test-optimization-validation/literal-glob.js +0 -52
  218. package/ci/test-optimization-validation/manifest-loader.js +0 -116
  219. package/ci/test-optimization-validation/manifest-scaffold.js +0 -1276
  220. package/ci/test-optimization-validation/manifest-schema.js +0 -695
  221. package/ci/test-optimization-validation/offline-fixtures.js +0 -335
  222. package/ci/test-optimization-validation/offline-output.js +0 -406
  223. package/ci/test-optimization-validation/package-check.js +0 -97
  224. package/ci/test-optimization-validation/payload-normalizer.js +0 -72
  225. package/ci/test-optimization-validation/plan-writer.js +0 -541
  226. package/ci/test-optimization-validation/preflight-runner.js +0 -186
  227. package/ci/test-optimization-validation/project-build-artifact.js +0 -31
  228. package/ci/test-optimization-validation/redaction.js +0 -319
  229. package/ci/test-optimization-validation/report-writer.js +0 -666
  230. package/ci/test-optimization-validation/result-semantics.js +0 -103
  231. package/ci/test-optimization-validation/runner-command.js +0 -264
  232. package/ci/test-optimization-validation/runner-contract.js +0 -695
  233. package/ci/test-optimization-validation/safe-files.js +0 -202
  234. package/ci/test-optimization-validation/scenarios/auto-test-retries.js +0 -171
  235. package/ci/test-optimization-validation/scenarios/basic-reporting.js +0 -407
  236. package/ci/test-optimization-validation/scenarios/ci-wiring.js +0 -666
  237. package/ci/test-optimization-validation/scenarios/early-flake-detection.js +0 -142
  238. package/ci/test-optimization-validation/scenarios/helpers.js +0 -621
  239. package/ci/test-optimization-validation/scenarios/test-management.js +0 -219
  240. package/ci/test-optimization-validation/source-text.js +0 -84
  241. package/ci/test-optimization-validation/static-diagnosis.js +0 -166
  242. package/ci/test-optimization-validation/test-output.js +0 -120
  243. package/ci/test-optimization-validation/validation-blocker.js +0 -21
  244. package/ci/validate-test-optimization.js +0 -3
  245. package/packages/datadog-esbuild/src/resolver.js +0 -284
  246. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/index.js +0 -156
  247. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/msgpack-to-json.js +0 -287
  248. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/payload-projection.js +0 -84
  249. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/sink.js +0 -368
  250. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/writer.js +0 -59
@@ -20,6 +20,8 @@ const {
20
20
  GIT_COMMIT_SHA,
21
21
  GIT_BRANCH,
22
22
  GIT_REPOSITORY_URL,
23
+ GIT_CHECKOUT_ROOT,
24
+ GIT_CHECKOUT_IS_CUSTOM,
23
25
  GIT_TAG,
24
26
  GIT_COMMIT_MESSAGE,
25
27
  GIT_COMMIT_COMMITTER_DATE,
@@ -39,6 +41,7 @@ const {
39
41
  } = require('./tags')
40
42
  const { filterSensitiveInfoFromRepository } = require('./url')
41
43
  const { cachedExec } = require('./git-cache')
44
+ const { validateGitCommitSha } = require('./user-provided-git')
42
45
 
43
46
  /** @typedef {NonNullable<ReturnType<string['match']>>} RegExpMatch */
44
47
 
@@ -46,6 +49,18 @@ const legacyStorage = storage('legacy')
46
49
 
47
50
  const GIT_REV_LIST_MAX_BUFFER = 12 * 1024 * 1024 // 12MB
48
51
 
52
+ function getGitEnvironment () {
53
+ const env = { ...getEnvironmentVariables() }
54
+ // Git resolves repository locations before moving from a project subdirectory to the worktree root.
55
+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR']) {
56
+ if (env[key] && !path.isAbsolute(env[key])) {
57
+ // Keep POSIX symlink/.. traversal; Windows also supports drive-relative paths.
58
+ env[key] = path.sep === '\\' ? path.resolve(env[key]) : `${process.cwd()}${path.sep}${env[key]}`
59
+ }
60
+ }
61
+ return env
62
+ }
63
+
49
64
  function sanitizedExec (
50
65
  flags,
51
66
  operationMetric,
@@ -65,10 +80,12 @@ function sanitizedExec (
65
80
  try {
66
81
  const exec = executionOptions?.uncached ? execFileSync : cachedExec
67
82
  /** @type {import('node:child_process').ExecFileSyncOptions} */
68
- const options = { stdio: 'pipe' }
83
+ const options = { stdio: 'pipe', env: getGitEnvironment() }
84
+ if (executionOptions?.cwd) options.cwd = executionOptions.cwd
69
85
  if (executionOptions?.timeout) options.timeout = executionOptions.timeout
70
86
  if (executionOptions?.localOnly) {
71
- options.env = { ...getEnvironmentVariables(), GIT_NO_LAZY_FETCH: '1', GIT_ALLOW_PROTOCOL: '' }
87
+ options.env.GIT_NO_LAZY_FETCH = '1'
88
+ options.env.GIT_ALLOW_PROTOCOL = ''
72
89
  }
73
90
  let result = exec('git', flags, options).toString()
74
91
 
@@ -118,19 +135,19 @@ function isGitAvailable () {
118
135
  }
119
136
  }
120
137
 
121
- function isShallowRepository (uncached = false) {
138
+ function isShallowRepository (uncached = false, cwd) {
122
139
  return sanitizedExec(
123
140
  ['rev-parse', '--is-shallow-repository'],
124
141
  { name: TELEMETRY_GIT_COMMAND, tags: { command: 'check_shallow' } },
125
142
  { name: TELEMETRY_GIT_COMMAND_MS, tags: { command: 'check_shallow' } },
126
143
  { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'check_shallow' } },
127
144
  true,
128
- { uncached }
145
+ { uncached, cwd }
129
146
  ) === 'true'
130
147
  }
131
148
 
132
- function getGitVersion () {
133
- const gitVersionString = sanitizedExec(['version'])
149
+ function getGitVersion (cwd) {
150
+ const gitVersionString = sanitizedExec(['version'], null, null, null, true, { cwd })
134
151
  const gitVersionMatches = /** @type {RegExpMatch} */ (gitVersionString.match(/git version (\d+)\.(\d+)\.(\d+)/))
135
152
  try {
136
153
  return {
@@ -143,8 +160,9 @@ function getGitVersion () {
143
160
  }
144
161
  }
145
162
 
146
- function unshallowRepository (parentOnly = false) {
147
- const gitVersion = getGitVersion()
163
+ function unshallowRepository (parentOnly = false, commitSha, cwd) {
164
+ if (commitSha && !validateGitCommitSha(commitSha)) return
165
+ const gitVersion = getGitVersion(cwd)
148
166
  if (!gitVersion) {
149
167
  log.warn('Git version could not be extracted, so git unshallow will not proceed')
150
168
  return
@@ -153,12 +171,19 @@ function unshallowRepository (parentOnly = false) {
153
171
  log.warn('Git version is <2.27, so git unshallow will not proceed')
154
172
  return
155
173
  }
156
- const defaultRemoteName = sanitizedExec(['config', '--default', 'origin', '--get', 'clone.defaultRemoteName'])
157
- const revParseHead = sanitizedExec(['rev-parse', 'HEAD'])
174
+ const defaultRemoteName = getGitRemoteName(cwd)
175
+ const checkoutHead = sanitizedExec(['rev-parse', 'HEAD'], null, null, null, true, { uncached: true, cwd })
176
+ const revParseHead = commitSha || checkoutHead
177
+ const targetedRecovery = commitSha && commitSha.toLowerCase() !== checkoutHead.toLowerCase()
178
+ /** @type {import('node:child_process').ExecFileSyncOptionsWithBufferEncoding} */
179
+ const fetchOptions = { stdio: 'pipe', env: getGitEnvironment() }
180
+ if (cwd) fetchOptions.cwd = cwd
181
+ if (targetedRecovery) fetchOptions.timeout = 5000
182
+ const depth = parentOnly ? '--deepen=1' : '--shallow-since="1 month ago"'
158
183
 
159
184
  const baseGitOptions = [
160
185
  'fetch',
161
- parentOnly ? '--deepen=1' : '--shallow-since="1 month ago"',
186
+ depth,
162
187
  '--update-shallow',
163
188
  '--filter=blob:none',
164
189
  '--recurse-submodules=no',
@@ -172,7 +197,7 @@ function unshallowRepository (parentOnly = false) {
172
197
  revParseHead,
173
198
  ]
174
199
  try {
175
- cachedExec('git', flags)
200
+ execFileSync('git', flags, fetchOptions)
176
201
  } catch (err) {
177
202
  // If the local HEAD is a commit that has not been pushed to the remote, the above command will fail.
178
203
  // eslint-disable-next-line eslint-rules/eslint-log-printf-style
@@ -181,15 +206,29 @@ function unshallowRepository (parentOnly = false) {
181
206
  TELEMETRY_GIT_COMMAND_ERRORS,
182
207
  { command: 'unshallow', errorType: err.code, exitCode: err.status || err.errno }
183
208
  )
209
+ if (targetedRecovery) {
210
+ const timeout = 5000 - (Date.now() - start)
211
+ if (timeout > 0 && !hasLocalGitObject(revParseHead, cwd)) {
212
+ sanitizedExec(
213
+ ['fetch', '--depth=1', ...baseGitOptions.slice(2), revParseHead],
214
+ null, null,
215
+ { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'unshallow' } },
216
+ true,
217
+ { uncached: true, timeout, expectedFailure: true, cwd }
218
+ )
219
+ }
220
+ return
221
+ }
184
222
  const upstreamRemote = sanitizedExec(
185
- ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}']
223
+ ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}'],
224
+ null, null, null, true, { uncached: true, cwd }
186
225
  )
187
226
  flags = [
188
227
  ...baseGitOptions,
189
228
  upstreamRemote,
190
229
  ]
191
230
  try {
192
- cachedExec('git', flags)
231
+ execFileSync('git', flags, fetchOptions)
193
232
  } catch (err) {
194
233
  // If the CI is working on a detached HEAD or branch tracking hasn't been set up, the above command will fail.
195
234
  // eslint-disable-next-line eslint-rules/eslint-log-printf-style
@@ -203,30 +242,52 @@ function unshallowRepository (parentOnly = false) {
203
242
  baseGitOptions,
204
243
  null,
205
244
  null,
206
- { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'unshallow' } } // we log the error in sanitizedExec
245
+ { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'unshallow' } }, // we log the error in sanitizedExec
246
+ true,
247
+ { uncached: true, cwd }
207
248
  )
208
249
  }
209
250
  }
210
251
  distributionMetric(TELEMETRY_GIT_COMMAND_MS, { command: 'unshallow' }, Date.now() - start)
211
252
  }
212
253
 
213
- function getRepositoryUrl () {
254
+ function getRepositoryUrl (cwd) {
214
255
  return sanitizedExec(
215
- ['config', '--get', 'remote.origin.url'],
256
+ ['remote', 'get-url', getGitRemoteName(cwd)],
216
257
  { name: TELEMETRY_GIT_COMMAND, tags: { command: 'get_repository' } },
217
258
  { name: TELEMETRY_GIT_COMMAND_MS, tags: { command: 'get_repository' } },
218
- { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'get_repository' } }
259
+ { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'get_repository' } },
260
+ true,
261
+ { uncached: true, cwd }
219
262
  )
220
263
  }
221
264
 
222
- function getLatestCommits () {
265
+ /**
266
+ * @param {string=} commitSha
267
+ * @param {string=} cwd
268
+ */
269
+ function getLatestCommits (commitSha, cwd) {
270
+ if (commitSha && !validateGitCommitSha(commitSha)) return []
223
271
  incrementCountMetric(TELEMETRY_GIT_COMMAND, { command: 'get_local_commits' })
224
272
  const startTime = Date.now()
225
273
  try {
226
- const result = cachedExec('git', ['log', '--format=%H', '-n 1000', '--since="1 month ago"'])
274
+ const flags = ['log', '--format=%H', '-n 1000', '--since="1 month ago"']
275
+ if (commitSha) flags.push(commitSha, '--')
276
+ const env = { ...getGitEnvironment(), GIT_NO_LAZY_FETCH: '1', GIT_ALLOW_PROTOCOL: '' }
277
+ /** @type {import('node:child_process').ExecFileSyncOptionsWithBufferEncoding} */
278
+ const options = { stdio: 'pipe', env }
279
+ if (cwd) options.cwd = cwd
280
+ const result = execFileSync('git', flags, options)
227
281
  .toString()
228
282
  .split('\n')
229
283
  .filter(Boolean)
284
+ if (commitSha && !result.includes(commitSha)) {
285
+ const selectedCommit = execFileSync('git',
286
+ ['rev-parse', '--verify', commitSha + '^{commit}'], options)
287
+ .toString().trim()
288
+ if (selectedCommit !== commitSha) return []
289
+ result.unshift(commitSha)
290
+ }
230
291
  distributionMetric(TELEMETRY_GIT_COMMAND_MS, { command: 'get_local_commits' }, Date.now() - startTime)
231
292
  return result
232
293
  } catch (err) {
@@ -239,12 +300,12 @@ function getLatestCommits () {
239
300
  }
240
301
  }
241
302
 
242
- function getGitDiff (baseCommit, targetCommit) {
303
+ function getGitDiff (baseCommit, targetCommit, cwd) {
243
304
  // Fetch the required snapshots explicitly; a depth-1 metadata fetch does not provide their ancestry.
244
305
  for (const commit of targetCommit ? [baseCommit, targetCommit] : [baseCommit]) {
245
- if (!hasLocalGitObject(commit)) {
306
+ if (!hasLocalGitObject(commit, cwd)) {
246
307
  // Use the current checkout state so a stale cache cannot shorten a complete clone.
247
- fetchHeadCommitSha(commit, isShallowRepository(true))
308
+ fetchHeadCommitSha(commit, isShallowRepository(true, cwd), cwd)
248
309
  }
249
310
  }
250
311
  const flags = ['diff', '-U0', '--word-diff=porcelain', baseCommit]
@@ -257,51 +318,90 @@ function getGitDiff (baseCommit, targetCommit) {
257
318
  { name: TELEMETRY_GIT_COMMAND_MS, tags: { command: 'diff' } },
258
319
  { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'diff' } },
259
320
  false, // important not to trim or we'll lose the line breaks which we need to detect impacted tests
260
- { uncached: true }
321
+ { uncached: true, cwd }
261
322
  )
262
323
  }
263
324
 
264
- function getGitRemoteName () {
265
- const upstreamRemote = sanitizedExec(
266
- ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}'],
325
+ function getGitRemoteName (cwd) {
326
+ const branchRef = sanitizedExec(
327
+ ['symbolic-ref', '--quiet', 'HEAD'],
267
328
  { name: TELEMETRY_GIT_COMMAND, tags: { command: 'get_remote_name' } },
268
329
  { name: TELEMETRY_GIT_COMMAND_MS, tags: { command: 'get_remote_name' } },
269
330
  { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'get_remote_name' } },
270
331
  true,
271
- { expectedFailure: true } // Detached HEADs and branches without an upstream use the remote-list fallback.
332
+ { expectedFailure: true, uncached: true, cwd } // Detached HEADs use the checkout-local fallback.
272
333
  )
273
334
 
274
- if (upstreamRemote) {
275
- return getSegment(upstreamRemote, '/', 0)
276
- }
277
-
278
335
  const remotes = sanitizedExec(
279
336
  ['remote'],
280
337
  { name: TELEMETRY_GIT_COMMAND, tags: { command: 'get_remote_name' } },
281
338
  { name: TELEMETRY_GIT_COMMAND_MS, tags: { command: 'get_remote_name' } },
282
339
  { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'get_remote_name' } },
283
- false
340
+ false,
341
+ { uncached: true, cwd }
284
342
  )
285
343
 
286
- return getSegment(remotes, '\n', 0) || 'origin'
344
+ if (!remotes) return 'origin'
345
+
346
+ const remoteNames = remotes.trim().split(/\r?\n/)
347
+ const branch = branchRef.replace(/^refs\/heads\//, '')
348
+ if (branch) {
349
+ // Read the configured remote: custom fetch refspecs can use any ref namespace.
350
+ const branchRemote = sanitizedExec(
351
+ ['config', '--get', `branch.${branch}.remote`],
352
+ { name: TELEMETRY_GIT_COMMAND, tags: { command: 'get_remote_name' } },
353
+ { name: TELEMETRY_GIT_COMMAND_MS, tags: { command: 'get_remote_name' } },
354
+ { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'get_remote_name' } },
355
+ true,
356
+ { expectedFailure: true, uncached: true, cwd }
357
+ )
358
+ if (branchRemote !== '.' && remoteNames.includes(branchRemote)) return branchRemote
359
+ }
360
+ const configuredRemote = sanitizedExec(
361
+ ['config', '--local', '--get', 'clone.defaultRemoteName'],
362
+ { name: TELEMETRY_GIT_COMMAND, tags: { command: 'get_remote_name' } },
363
+ { name: TELEMETRY_GIT_COMMAND_MS, tags: { command: 'get_remote_name' } },
364
+ { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'get_remote_name' } },
365
+ true,
366
+ { expectedFailure: true, uncached: true, cwd }
367
+ )
368
+
369
+ if (configuredRemote && remoteNames.includes(configuredRemote)) return configuredRemote
370
+ // Clone -o overrides remain in local branch tracking after HEAD is detached.
371
+ const trackingConfiguration = sanitizedExec(
372
+ ['config', '--local', '--get-regexp', String.raw`^branch\..*\.remote$`],
373
+ { name: TELEMETRY_GIT_COMMAND, tags: { command: 'get_remote_name' } },
374
+ { name: TELEMETRY_GIT_COMMAND_MS, tags: { command: 'get_remote_name' } },
375
+ { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'get_remote_name' } },
376
+ false,
377
+ { expectedFailure: true, uncached: true, cwd }
378
+ )
379
+ const trackingRemotes = new Set(trackingConfiguration.split(/\r?\n/)
380
+ .map(line => getSegment(line, ' ', 1)).filter(remote => remote && remoteNames.includes(remote)))
381
+ if (trackingRemotes.size === 1) return trackingRemotes.values().next().value
382
+ return remoteNames.includes('origin') ? 'origin' : remoteNames[0] || 'origin'
287
383
  }
288
384
 
289
- function getSourceBranch () {
385
+ function getSourceBranch (cwd) {
290
386
  return sanitizedExec(
291
387
  ['rev-parse', '--abbrev-ref', 'HEAD'],
292
388
  { name: TELEMETRY_GIT_COMMAND, tags: { command: 'get_source_branch' } },
293
389
  { name: TELEMETRY_GIT_COMMAND_MS, tags: { command: 'get_source_branch' } },
294
- { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'get_source_branch' } }
390
+ { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'get_source_branch' } },
391
+ true, { cwd }
295
392
  )
296
393
  }
297
394
 
298
- function checkAndFetchBranch (branch, remoteName) {
395
+ function checkAndFetchBranch (branch, remoteName, cwd) {
396
+ const options = { stdio: 'pipe', env: getGitEnvironment() }
397
+ if (cwd) options.cwd = cwd
299
398
  try {
300
399
  // `git show-ref --verify --quiet refs/remotes/${remoteName}/${branch}` will exit 0 if the branch exists
301
400
  // Otherwise it will exit 1
302
401
  cachedExec(
303
402
  'git',
304
403
  ['show-ref', '--verify', '--quiet', `refs/remotes/${remoteName}/${branch}`],
404
+ options
305
405
  )
306
406
  // branch exists locally, so we finish
307
407
  } catch {
@@ -314,14 +414,14 @@ function checkAndFetchBranch (branch, remoteName) {
314
414
  const remoteHeads = cachedExec(
315
415
  'git',
316
416
  ['ls-remote', '--heads', remoteName, branch],
317
- { stdio: 'pipe', timeout: 2000 }
417
+ { ...options, timeout: 2000 }
318
418
  )
319
419
  if (remoteHeads) {
320
420
  // branch exists, so we'll fetch it
321
421
  cachedExec(
322
422
  'git',
323
423
  ['fetch', '--depth', '1', remoteName, branch],
324
- { stdio: 'pipe', timeout: 5000 }
424
+ { ...options, timeout: 5000 }
325
425
  )
326
426
  }
327
427
  } catch (err) {
@@ -331,13 +431,13 @@ function checkAndFetchBranch (branch, remoteName) {
331
431
  }
332
432
  }
333
433
 
334
- function getLocalBranches (remoteName) {
434
+ function getLocalBranches (remoteName, cwd) {
335
435
  const localBranches = sanitizedExec(
336
436
  ['for-each-ref', '--format=%(refname:short)', `refs/remotes/${remoteName}`],
337
437
  { name: TELEMETRY_GIT_COMMAND, tags: { command: 'get_local_branches' } },
338
438
  { name: TELEMETRY_GIT_COMMAND_MS, tags: { command: 'get_local_branches' } },
339
439
  { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'get_local_branches' } },
340
- false
440
+ false, { cwd }
341
441
  )
342
442
  try {
343
443
  return localBranches.split('\n').filter(Boolean)
@@ -346,21 +446,23 @@ function getLocalBranches (remoteName) {
346
446
  }
347
447
  }
348
448
 
349
- function getMergeBase (baseBranch, sourceBranch) {
449
+ function getMergeBase (baseBranch, sourceBranch, cwd) {
350
450
  return sanitizedExec(
351
451
  ['merge-base', baseBranch, sourceBranch],
352
452
  { name: TELEMETRY_GIT_COMMAND, tags: { command: 'get_merge_base' } },
353
453
  { name: TELEMETRY_GIT_COMMAND_MS, tags: { command: 'get_merge_base' } },
354
- { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'get_merge_base' } }
454
+ { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'get_merge_base' } },
455
+ true, { cwd }
355
456
  )
356
457
  }
357
458
 
358
- function getCounts (sourceBranch, candidateBranch) {
459
+ function getCounts (sourceBranch, candidateBranch, cwd) {
359
460
  const counts = sanitizedExec(
360
461
  ['rev-list', '--left-right', '--count', `${candidateBranch}...${sourceBranch}`],
361
462
  { name: TELEMETRY_GIT_COMMAND, tags: { command: 'get_counts' } },
362
463
  { name: TELEMETRY_GIT_COMMAND_MS, tags: { command: 'get_counts' } },
363
- { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'get_counts' } }
464
+ { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'get_counts' } },
465
+ true, { cwd }
364
466
  )
365
467
  try {
366
468
  if (!counts) {
@@ -373,15 +475,28 @@ function getCounts (sourceBranch, candidateBranch) {
373
475
  }
374
476
  }
375
477
 
376
- function getCommitsRevList (commitsToExclude, commitsToInclude) {
377
- let result = null
478
+ /**
479
+ * @param {string[]} commitsToExclude
480
+ * @param {string[]} commitsToInclude
481
+ * @param {boolean} [allowLazyFetch] Allow a bounded retry to hydrate promised objects.
482
+ * @param {string=} cwd
483
+ */
484
+ function getCommitsRevList (commitsToExclude, commitsToInclude, allowLazyFetch = false, cwd) {
485
+ let result
378
486
 
379
487
  const commitsToExcludeString = commitsToExclude.map(commit => `^${commit}`)
380
488
 
381
489
  incrementCountMetric(TELEMETRY_GIT_COMMAND, { command: 'get_objects' })
382
490
  const startTime = Date.now()
383
491
  try {
384
- result = cachedExec(
492
+ const env = allowLazyFetch
493
+ ? getGitEnvironment()
494
+ : { ...getGitEnvironment(), GIT_NO_LAZY_FETCH: '1', GIT_ALLOW_PROTOCOL: '' }
495
+ /** @type {import('node:child_process').ExecFileSyncOptions} */
496
+ const options = { stdio: 'pipe', maxBuffer: GIT_REV_LIST_MAX_BUFFER, env }
497
+ if (cwd) options.cwd = cwd
498
+ if (allowLazyFetch) options.timeout = 5000
499
+ result = execFileSync(
385
500
  'git',
386
501
  [
387
502
  'rev-list',
@@ -389,14 +504,31 @@ function getCommitsRevList (commitsToExclude, commitsToInclude) {
389
504
  '--no-object-names',
390
505
  '--filter=blob:none',
391
506
  '--since="1 month ago"',
507
+ '--max-count=1000',
392
508
  ...commitsToExcludeString,
393
509
  ...commitsToInclude,
394
510
  ],
395
- { stdio: 'pipe', maxBuffer: GIT_REV_LIST_MAX_BUFFER })
511
+ options)
396
512
  .toString()
397
513
  .split('\n')
398
514
  .filter(Boolean)
515
+ const objects = new Set(result)
516
+ // Only the first root can be the old selection prepended by getLatestCommits; other roots came from its window.
517
+ const selectedCommit = commitsToInclude[0]
518
+ if (validateGitCommitSha(selectedCommit) && !objects.has(selectedCommit) &&
519
+ !commitsToExclude.includes(selectedCommit)) {
520
+ if (allowLazyFetch) {
521
+ options.timeout = 5000 - (Date.now() - startTime)
522
+ if (options.timeout <= 0) throw new Error('Git object hydration timed out')
523
+ }
524
+ const selectedObjects = execFileSync('git', [
525
+ 'rev-list', '--objects', '--no-object-names', '--filter=blob:none', '--max-count=1',
526
+ ...commitsToExcludeString, selectedCommit,
527
+ ], options).toString().split('\n').filter(Boolean)
528
+ result = [...new Set([...result, ...selectedObjects])]
529
+ }
399
530
  } catch (err) {
531
+ result = null
400
532
  log.error('Get commits to upload failed', err)
401
533
  incrementCountMetric(
402
534
  TELEMETRY_GIT_COMMAND_ERRORS,
@@ -407,7 +539,7 @@ function getCommitsRevList (commitsToExclude, commitsToInclude) {
407
539
  return result
408
540
  }
409
541
 
410
- function generatePackFilesForCommits (commitsToUpload) {
542
+ function generatePackFilesForCommits (commitsToUpload, cwd) {
411
543
  let result = []
412
544
  const tmpFolder = os.tmpdir()
413
545
 
@@ -419,13 +551,16 @@ function generatePackFilesForCommits (commitsToUpload) {
419
551
 
420
552
  const randomPrefix = String(Math.floor(Math.random() * 10_000))
421
553
  const temporaryPath = path.join(tmpFolder, randomPrefix)
422
- const cwdPath = path.join(process.cwd(), randomPrefix)
554
+ const cwdPath = path.join(cwd || process.cwd(), randomPrefix)
423
555
 
424
556
  incrementCountMetric(TELEMETRY_GIT_COMMAND, { command: 'pack_objects' })
425
557
  const startTime = Date.now()
426
558
  // Generates pack files to upload and
427
559
  // returns the ordered list of packfiles' paths
428
560
  function execGitPackObjects (targetPath) {
561
+ /** @type {import('node:child_process').ExecFileSyncOptionsWithBufferEncoding} */
562
+ const options = { stdio: 'pipe', input: commitsToUpload.join('\n'), env: getGitEnvironment() }
563
+ if (cwd) options.cwd = cwd
429
564
  return cachedExec(
430
565
  'git',
431
566
  [
@@ -434,7 +569,7 @@ function generatePackFilesForCommits (commitsToUpload) {
434
569
  '--max-pack-size=3m',
435
570
  targetPath,
436
571
  ],
437
- { stdio: 'pipe', input: commitsToUpload.join('\n') }
572
+ options
438
573
  ).toString().split('\n').filter(Boolean).map(commit => `${targetPath}-${commit}.pack`)
439
574
  }
440
575
 
@@ -473,13 +608,22 @@ function generatePackFilesForCommits (commitsToUpload) {
473
608
  return result
474
609
  }
475
610
 
476
- function getRepositoryRoot () {
611
+ function getRepositoryRoot (cwd) {
477
612
  return sanitizedExec(
478
- ['rev-parse', '--show-toplevel']
613
+ ['rev-parse', '--show-toplevel'], null, null, null, true, { uncached: true, cwd }
479
614
  )
480
615
  }
481
616
 
482
- // If there is ciMetadata, it takes precedence.
617
+ /**
618
+ * Read mutable checkout metadata without the cache shared by CI jobs.
619
+ * @param {string[]} flags
620
+ * @param {boolean} [shouldTrim]
621
+ * @param {string=} cwd
622
+ */
623
+ function readCheckout (flags, shouldTrim = true, cwd) {
624
+ return sanitizedExec(flags, null, null, null, shouldTrim, { uncached: true, cwd })
625
+ }
626
+
483
627
  function getGitMetadata (ciMetadata) {
484
628
  const {
485
629
  commitSHA,
@@ -493,6 +637,7 @@ function getGitMetadata (ciMetadata) {
493
637
  headCommitSha,
494
638
  pullRequestBaseBranchSha,
495
639
  } = ciMetadata
640
+ const gitRoot = getRepositoryRoot()
496
641
 
497
642
  // With stdio: 'pipe', errors in this command will not be output to the parent process,
498
643
  // so if `git` is not present in the env, we won't show a warning to the user.
@@ -503,36 +648,63 @@ function getGitMetadata (ciMetadata) {
503
648
  committerName,
504
649
  committerEmail,
505
650
  committerDate,
506
- ] = sanitizedExec(['show', '-s', '--format=%an,%ae,%aI,%cn,%ce,%cI']).split(',')
651
+ ] = readCheckout([
652
+ 'show', '-s', '--no-show-signature', '--format=%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI',
653
+ ], true, gitRoot).split('\0')
507
654
 
508
655
  const tags = {
509
656
  [GIT_COMMIT_MESSAGE]:
510
- commitMessage || sanitizedExec(['show', '-s', '--format=%B'], null, null, null, false),
511
- [GIT_BRANCH]: branch || sanitizedExec(['rev-parse', '--abbrev-ref', 'HEAD']),
512
- [GIT_COMMIT_SHA]: commitSHA || sanitizedExec(['rev-parse', 'HEAD']),
513
- [CI_WORKSPACE_PATH]: ciWorkspacePath || getRepositoryRoot(),
657
+ commitMessage || readCheckout(['show', '-s', '--no-show-signature', '--format=%B'], false, gitRoot),
658
+ [GIT_BRANCH]: branch || readCheckout(['rev-parse', '--abbrev-ref', 'HEAD'], true, gitRoot),
659
+ [GIT_COMMIT_SHA]: commitSHA || readCheckout(['rev-parse', 'HEAD'], true, gitRoot),
660
+ [CI_WORKSPACE_PATH]: ciWorkspacePath || gitRoot,
661
+ }
662
+
663
+ if (gitRoot) {
664
+ tags[GIT_CHECKOUT_ROOT] = gitRoot
665
+ if (ciWorkspacePath) {
666
+ let workspacePath = path.resolve(ciWorkspacePath)
667
+ let checkoutPath = path.resolve(gitRoot)
668
+ try {
669
+ workspacePath = fs.realpathSync.native(workspacePath)
670
+ checkoutPath = fs.realpathSync.native(checkoutPath)
671
+ } catch {
672
+ // A provider may report a host path that is not mounted in the test container.
673
+ }
674
+ if (workspacePath !== checkoutPath) tags[GIT_CHECKOUT_IS_CUSTOM] = 'true'
675
+ }
676
+ }
677
+
678
+ if (tags[GIT_BRANCH] === 'HEAD') delete tags[GIT_BRANCH]
679
+
680
+ let localTag = tag
681
+ if (!localTag && !tags[GIT_BRANCH]) {
682
+ const tagsAtHead = readCheckout(['tag', '--no-column', '--points-at', 'HEAD'], false, gitRoot)
683
+ .trim().split(/\r?\n/).filter(Boolean)
684
+ if (tagsAtHead.length === 1) localTag = tagsAtHead[0]
514
685
  }
515
686
 
516
687
  if (headCommitSha) {
517
- const shallow = isShallowRepository(true)
518
- const fetchedAtDepthOne = shallow && fetchHeadCommitSha(headCommitSha)
688
+ const shallow = isShallowRepository(true, gitRoot)
689
+ const fetchedAtDepthOne = shallow && fetchHeadCommitSha(headCommitSha, true, gitRoot)
519
690
  const headFlags = [
520
691
  'show',
521
692
  '-s',
522
- '--format=\'%H","%aI","%an","%ae","%cI","%cn","%ce","%B\'',
693
+ '--no-show-signature',
694
+ '--format=%H%x00%aI%x00%an%x00%ae%x00%cI%x00%cn%x00%ce%x00%B',
523
695
  headCommitSha,
524
696
  ]
525
697
  // Only explicit, bounded fetches may contact the remote during head metadata recovery.
526
- const headOptions = { uncached: true, localOnly: true }
698
+ const headOptions = { uncached: true, localOnly: true, cwd: gitRoot }
527
699
  let headInfo = sanitizedExec(headFlags, null, null, null, false, headOptions)
528
700
  if (!headInfo && (fetchedAtDepthOne || !shallow)) {
529
- fetchHeadCommitSha(headCommitSha, false)
701
+ fetchHeadCommitSha(headCommitSha, false, gitRoot)
530
702
  headInfo = sanitizedExec(headFlags, null, null, null, false, headOptions)
531
703
  }
532
704
 
533
705
  // Prepare a known diff base while the remote is available, including when Git upload is disabled.
534
- if (shallow && pullRequestBaseBranchSha && !hasLocalGitObject(pullRequestBaseBranchSha)) {
535
- fetchHeadCommitSha(pullRequestBaseBranchSha)
706
+ if (shallow && pullRequestBaseBranchSha && !hasLocalGitObject(pullRequestBaseBranchSha, gitRoot)) {
707
+ fetchHeadCommitSha(pullRequestBaseBranchSha, true, gitRoot)
536
708
  }
537
709
 
538
710
  const [
@@ -544,7 +716,7 @@ function getGitMetadata (ciMetadata) {
544
716
  headCommitterName,
545
717
  headCommitterEmail,
546
718
  headCommitMessage,
547
- ] = headInfo.split('","')
719
+ ] = headInfo.split('\0')
548
720
 
549
721
  if (gitHeadCommitSha) {
550
722
  tags[GIT_COMMIT_HEAD_AUTHOR_DATE] = headAuthorDate
@@ -559,14 +731,14 @@ function getGitMetadata (ciMetadata) {
559
731
 
560
732
  const entries = [
561
733
  GIT_REPOSITORY_URL,
562
- filterSensitiveInfoFromRepository(repositoryUrl || sanitizedExec(['ls-remote', '--get-url'])),
734
+ filterSensitiveInfoFromRepository(repositoryUrl || getRepositoryUrl(gitRoot)),
563
735
  GIT_COMMIT_AUTHOR_DATE, authorDate,
564
736
  GIT_COMMIT_AUTHOR_NAME, ciAuthorName || authorName,
565
737
  GIT_COMMIT_AUTHOR_EMAIL, ciAuthorEmail || authorEmail,
566
738
  GIT_COMMIT_COMMITTER_DATE, committerDate,
567
739
  GIT_COMMIT_COMMITTER_NAME, committerName,
568
740
  GIT_COMMIT_COMMITTER_EMAIL, committerEmail,
569
- GIT_TAG, tag,
741
+ GIT_TAG, localTag,
570
742
  ]
571
743
 
572
744
  for (let i = 0; i < entries.length; i += 2) {
@@ -579,28 +751,36 @@ function getGitMetadata (ciMetadata) {
579
751
  return tags
580
752
  }
581
753
 
582
- function getGitInformationDiscrepancy () {
583
- const gitRepositoryUrl = getRepositoryUrl()
754
+ function getGitInformationDiscrepancy (cwd) {
755
+ const gitRepositoryUrl = getRepositoryUrl(cwd)
584
756
 
585
757
  const gitCommitSHA = sanitizedExec(
586
758
  ['rev-parse', 'HEAD'],
587
759
  { name: TELEMETRY_GIT_COMMAND, tags: { command: 'get_commit_sha' } },
588
760
  { name: TELEMETRY_GIT_COMMAND_MS, tags: { command: 'get_commit_sha' } },
589
- { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'get_commit_sha' } }
761
+ { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'get_commit_sha' } },
762
+ true,
763
+ { uncached: true, cwd }
590
764
  )
591
765
 
592
766
  return { gitRepositoryUrl, gitCommitSHA }
593
767
  }
594
768
 
595
- /** @param {string} sha */
596
- function hasLocalGitObject (sha) {
769
+ /**
770
+ * @param {string} sha
771
+ * @param {string=} cwd
772
+ */
773
+ function hasLocalGitObject (sha, cwd) {
597
774
  return legacyStorage.run({ noop: true }, () => {
598
775
  try {
599
- execFileSync('git', ['cat-file', '-e', sha], {
776
+ /** @type {import('node:child_process').ExecFileSyncOptionsWithBufferEncoding} */
777
+ const options = {
600
778
  stdio: 'pipe',
601
779
  // Older Git versions ignore GIT_NO_LAZY_FETCH, so also disallow transports for this local-only probe.
602
- env: { ...getEnvironmentVariables(), GIT_NO_LAZY_FETCH: '1', GIT_ALLOW_PROTOCOL: '' },
603
- })
780
+ env: { ...getGitEnvironment(), GIT_NO_LAZY_FETCH: '1', GIT_ALLOW_PROTOCOL: '' },
781
+ }
782
+ if (cwd) options.cwd = cwd
783
+ execFileSync('git', ['cat-file', '-e', sha], options)
604
784
  return true
605
785
  } catch {
606
786
  return false
@@ -608,10 +788,10 @@ function hasLocalGitObject (sha) {
608
788
  })
609
789
  }
610
790
 
611
- function fetchHeadCommitSha (headSha, useDepth = true) {
612
- const remoteName = getGitRemoteName()
791
+ function fetchHeadCommitSha (headSha, useDepth = true, cwd) {
792
+ const remoteName = getGitRemoteName(cwd)
613
793
  // Existing heads retain the original repair/history behavior; a failed bounded fetch also retries that path.
614
- const depths = useDepth && !hasLocalGitObject(headSha) ? [true, false] : [false]
794
+ const depths = useDepth && !hasLocalGitObject(headSha, cwd) ? [true, false] : [false]
615
795
  for (const shallow of depths) {
616
796
  try {
617
797
  sanitizedExec(
@@ -629,7 +809,7 @@ function fetchHeadCommitSha (headSha, useDepth = true) {
629
809
  { name: TELEMETRY_GIT_COMMAND_MS, tags: { command: 'fetch_head_commit_sha' } },
630
810
  { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'fetch_head_commit_sha' } },
631
811
  true,
632
- { uncached: true, throwOnError: true, timeout: 5000 }
812
+ { uncached: true, throwOnError: true, timeout: 5000, cwd }
633
813
  )
634
814
  return shallow
635
815
  } catch {
@@ -657,6 +837,7 @@ module.exports = {
657
837
  getLocalBranches,
658
838
  getMergeBase,
659
839
  getCounts,
840
+ hasLocalGitObject,
660
841
  fetchHeadCommitSha,
661
842
  getRepositoryRoot,
662
843
  }