@@ -33,6 +33,7 @@ const RAW_BUILTINS = require('module').builtinModules
33
33
const CHANNEL = 'dd-trace:bundler:load'
34
34
const path = require ( 'path' )
35
35
const fs = require ( 'fs' )
36
+ const { execSync } = require ( 'child_process' )
36
37
37
38
const builtins = new Set ( )
38
39
@@ -61,6 +62,39 @@ function isESMBuild (build) {
61
62
return format === 'esm' || outputFile ?. endsWith ( '.mjs' ) || outExtension === '.mjs'
62
63
}
63
64
65
+ function getGitMetadata ( ) {
66
+ const gitMetadata = {
67
+ repositoryURL : null ,
68
+ commitSHA : null
69
+ }
70
+
71
+ try {
72
+ gitMetadata . repositoryURL = execSync ( 'git config --get remote.origin.url' , {
73
+ encoding : 'utf8' ,
74
+ stdio : [ 'pipe' , 'pipe' , 'ignore' ] ,
75
+ cwd : process . cwd ( )
76
+ } ) . trim ( )
77
+ } catch ( e ) {
78
+ if ( DEBUG ) {
79
+ console . warn ( 'Warning: failed to get git repository URL:' , e . message )
80
+ }
81
+ }
82
+
83
+ try {
84
+ gitMetadata . commitSHA = execSync ( 'git rev-parse HEAD' , {
85
+ encoding : 'utf8' ,
86
+ stdio : [ 'pipe' , 'pipe' , 'ignore' ] ,
87
+ cwd : process . cwd ( )
88
+ } ) . trim ( )
89
+ } catch ( e ) {
90
+ if ( DEBUG ) {
91
+ console . warn ( 'Warning: failed to get git commit SHA:' , e . message )
92
+ }
93
+ }
94
+
95
+ return gitMetadata
96
+ }
97
+
64
98
module . exports . setup = function ( build ) {
65
99
const externalModules = new Set ( build . initialOptions . external || [ ] )
66
100
if ( isESMBuild ( build ) ) {
@@ -77,6 +111,28 @@ ${build.initialOptions.banner.js}`
77
111
}
78
112
}
79
113
114
+ // Get git metadata at build time and add it to the banner for both ESM and CommonJS builds
115
+ const gitMetadata = getGitMetadata ( )
116
+ if ( gitMetadata . repositoryURL || gitMetadata . commitSHA ) {
117
+ build . initialOptions . banner ??= { }
118
+ build . initialOptions . banner . js ??= ''
119
+
120
+ build . initialOptions . banner . js = `if (typeof process === 'object' && process !== null &&
121
+ process.env !== null && typeof process.env === 'object') {
122
+ ${ gitMetadata . repositoryURL ? `process.env.DD_GIT_REPOSITORY_URL = '${ gitMetadata . repositoryURL } ';` : '' }
123
+ ${ gitMetadata . commitSHA ? `process.env.DD_GIT_COMMIT_SHA = '${ gitMetadata . commitSHA } ';` : '' }
124
+ }
125
+ ${ build . initialOptions . banner . js } `
126
+
127
+ if ( DEBUG ) {
128
+ console . log ( 'Info: automatically injected git metadata:' )
129
+ console . log ( `DD_GIT_REPOSITORY_URL: ${ gitMetadata . repositoryURL || 'not available' } ` )
130
+ console . log ( `DD_GIT_COMMIT_SHA: ${ gitMetadata . commitSHA || 'not available' } ` )
131
+ }
132
+ } else if ( DEBUG ) {
133
+ console . warn ( 'Warning: No git metadata available - skipping injection' )
134
+ }
135
+
80
136
build . onResolve ( { filter : / .* / } , args => {
81
137
if ( externalModules . has ( args . path ) ) {
82
138
// Internal Node.js packages will still be instrumented via require()
0 commit comments