GitLabgitlab-org

cli

main
ply7 git calls403 ms106 KiB4 cachedprotocol v2
611 lines30 KiBRaw
1//go:build !integration
3package pm
5import (
6 "encoding/xml"
7 "errors"
8 "fmt"
9 "net/http"
10 "net/http/httptest"
11 "os"
12 "path/filepath"
13 "strings"
14 "testing"
16 "github.com/stretchr/testify/assert"
17 "github.com/stretchr/testify/require"
20func mirrorsXML(mirrors ...string) []byte {
21 body := "<settings xmlns=\"http://maven.apache.org/SETTINGS/1.0.0\">\n <mirrors>\n"
22 for _, m := range mirrors {
23 body += " " + m + "\n"
24 }
25 return []byte(body + " </mirrors>\n</settings>\n")
28func mirrorXML(id, mirrorOf, url string) string {
29 return "<mirror><id>" + id + "</id><mirrorOf>" + mirrorOf + "</mirrorOf><url>" + url + "</url></mirror>"
32const stockHTTPBlocker = `<mirror><id>maven-default-http-blocker</id><mirrorOf>external:http:*</mirrorOf><url>http://0.0.0.0/</url><blocked>true</blocked></mirror>`
34func TestMavenKnownMirrors(t *testing.T) {
35 nexus := mirrorXML("corp", "*", "https://nexus.example.com/repository/public/")
37 for _, tc := range []struct {
38 name string
39 user, global []byte
40 want []string
41 externalOnly bool
42 }{
43 {name: "when the user settings have a catch-all mirror", user: mirrorsXML(nexus), want: []string{"https://nexus.example.com/repository/public/"}},
44 {
45 name: "when the global settings have the catch-all", user: mirrorsXML(mirrorXML("c", "central", "https://central.example.com/maven2/")), global: mirrorsXML(nexus),
46 want: []string{"https://central.example.com/maven2/", "https://nexus.example.com/repository/public/"},
47 },
48 {
49 name: "when a mirror after the catch-all names a repository id", user: mirrorsXML(nexus, mirrorXML("c", "central", "https://central.example.com/maven2/")),
50 want: []string{"https://nexus.example.com/repository/public/", "https://central.example.com/maven2/"},
51 },
52 {
53 name: "when the catch-all is external:*", user: mirrorsXML(mirrorXML("corp", "external:*", "https://nexus.example.com/repository/public/")),
54 want: []string{"https://nexus.example.com/repository/public/"}, externalOnly: true,
55 },
56 {name: "when Maven's stock blocked mirror is there too", user: mirrorsXML(nexus), global: mirrorsXML(stockHTTPBlocker), want: []string{"https://nexus.example.com/repository/public/"}},
57 {name: "when there is no catch-all", user: mirrorsXML(mirrorXML("c", "central", "https://nexus.example.com/repository/public/"))},
58 {name: "when the catch-all excludes a repository", user: mirrorsXML(mirrorXML("corp", "*,!internal", "https://nexus.example.com/repository/public/"))},
59 {name: "when the catch-all lists other patterns", user: mirrorsXML(mirrorXML("corp", "*, central", "https://nexus.example.com/repository/public/"))},
60 {name: "when the external:* mirror is on localhost", user: mirrorsXML(mirrorXML("corp", "external:*", "http://localhost:8081/repository/public/"))},
61 {name: "when any mirror's URL comes from a property", user: mirrorsXML(nexus, mirrorXML("c", "central", "https://${env.CENTRAL_HOST}/maven2/"))},
62 {name: "when the catch-all's URL comes from a property", user: mirrorsXML(mirrorXML("corp", "*", "${env.NEXUS_URL}"))},
63 {name: "when a mirror's path comes from a property", user: mirrorsXML(mirrorXML("corp", "*", "https://nexus.example.com/${env.NEXUS_REPO}/"))},
64 {name: "when a mirror's URL isn't http or https", user: mirrorsXML(nexus, mirrorXML("f", "local", "file:///srv/maven/"))},
65 {name: "when the global settings can't be parsed", user: mirrorsXML(nexus), global: []byte("<settings><mirrors></settings>")},
66 {
67 name: "when the catch-all lists the default layout", user: mirrorsXML(`<mirror><id>corp</id><mirrorOf>*</mirrorOf><mirrorOfLayouts>default,legacy</mirrorOfLayouts><url>https://nexus.example.com/repository/public/</url></mirror>`),
68 want: []string{"https://nexus.example.com/repository/public/"},
69 },
70 {
71 name: "when the catch-all lists every layout but p2", user: mirrorsXML(`<mirror><id>corp</id><mirrorOf>*</mirrorOf><mirrorOfLayouts>*,!p2</mirrorOfLayouts><url>https://nexus.example.com/repository/public/</url></mirror>`),
72 want: []string{"https://nexus.example.com/repository/public/"},
73 },
74 {
75 name: "when the catch-all's layout is padded", user: mirrorsXML(`<mirror><id>corp</id><mirrorOf>*</mirrorOf><mirrorOfLayouts> default </mirrorOfLayouts><url>https://nexus.example.com/repository/public/</url></mirror>`),
76 want: []string{"https://nexus.example.com/repository/public/"},
77 },
78 {
79 name: "when a padded user mirror id hides the global catch-all",
80 user: mirrorsXML(`<mirror><id> corp </id><mirrorOf>central</mirrorOf><url>https://central.example.com/maven2/</url></mirror>`), global: mirrorsXML(nexus),
81 },
82 {name: "when the catch-all only mirrors another layout", user: mirrorsXML(`<mirror><id>corp</id><mirrorOf>*</mirrorOf><mirrorOfLayouts>p2</mirrorOfLayouts><url>https://nexus.example.com/repository/public/</url></mirror>`)},
83 {name: "when the catch-all excludes the default layout", user: mirrorsXML(`<mirror><id>corp</id><mirrorOf>*</mirrorOf><mirrorOfLayouts>*,!default</mirrorOfLayouts><url>https://nexus.example.com/repository/public/</url></mirror>`)},
84 {name: "when the catch-all's layouts come from a property", user: mirrorsXML(`<mirror><id>corp</id><mirrorOf>*</mirrorOf><mirrorOfLayouts>${env.LAYOUTS}</mirrorOfLayouts><url>https://nexus.example.com/repository/public/</url></mirror>`)},
85 {
86 name: "when a user mirror's id hides the global catch-all",
87 user: mirrorsXML(mirrorXML("corp", "central", "https://central.example.com/maven2/")), global: mirrorsXML(nexus),
88 },
89 {
90 name: "when two mirrors without an id hide the global catch-all",
91 user: mirrorsXML(`<mirror><mirrorOf>central</mirrorOf><url>https://central.example.com/maven2/</url></mirror>`), global: mirrorsXML(`<mirror><mirrorOf>*</mirrorOf><url>https://nexus.example.com/repository/public/</url></mirror>`),
92 },
93 {
94 name: "when a user mirror without an id hides a global catch-all with id default",
95 user: mirrorsXML(`<mirror><mirrorOf>central</mirrorOf><url>https://central.example.com/maven2/</url></mirror>`), global: mirrorsXML(mirrorXML("default", "*", "https://nexus.example.com/repository/public/")),
96 },
97 {
98 name: "when a user mirror's id hides another global mirror", user: mirrorsXML(nexus), global: mirrorsXML(mirrorXML("corp", "central", "https://central.example.com/maven2/")),
99 want: []string{"https://nexus.example.com/repository/public/", "https://central.example.com/maven2/"},
100 },
101 {
102 name: "when the user settings repeat a mirror id", user: mirrorsXML(nexus, mirrorXML("corp", "central", "https://central.example.com/maven2/")),
103 want: []string{"https://nexus.example.com/repository/public/", "https://central.example.com/maven2/"},
104 },
105 {name: "when a catch-all repeats an earlier mirror's id", user: mirrorsXML(mirrorXML("corp", "central", "https://central.example.com/maven2/"), nexus)},
106 {name: "when a catch-all repeats a blocked mirror's id", user: mirrorsXML(`<mirror><id>corp</id><mirrorOf>central</mirrorOf><url>http://0.0.0.0/</url><blocked>true</blocked></mirror>`, nexus)},
107 {name: "when a mirror id comes from a property", user: mirrorsXML(mirrorXML("${env.MIRROR_ID}", "central", "https://central.example.com/maven2/")), global: mirrorsXML(nexus)},
108 {name: "when there are no settings at all"},
109 } {
110 t.Run(tc.name, func(t *testing.T) {
111 urls, externalOnly, ok := mavenKnownMirrors(tc.user, tc.global)
113 if tc.want == nil {
114 assert.False(t, ok, "glab can't know every mirror Maven may use, so it must keep guessing")
115 return
116 }
117 require.True(t, ok)
118 var got []string
119 for _, u := range urls {
120 got = append(got, u.String())
121 }
122 assert.Equal(t, tc.want, got)
123 assert.Equal(t, tc.externalOnly, externalOnly)
124 })
125 }
128// stockM2Conf is Maven 3.9's bin/m2.conf.
129const stockM2Conf = `main is org.apache.maven.cli.MavenCli from plexus.core
131set maven.conf default ${maven.home}/conf
133[plexus.core]
134load ${maven.conf}/logging
135optionally ${maven.home}/lib/ext/*.jar
136load ${maven.home}/lib/*.jar
139// fakeMavenInstall creates a Maven 3 install at home and returns its bin/mvn.
140func fakeMavenInstall(t *testing.T, home string) string {
141 t.Helper()
142 for _, dir := range []string{"bin", "conf", "lib"} {
143 require.NoError(t, os.MkdirAll(filepath.Join(home, dir), 0o700))
144 }
145 require.NoError(t, os.WriteFile(filepath.Join(home, "bin", "mvn"), []byte("#!/bin/sh\n"), 0o700))
146 require.NoError(t, os.WriteFile(filepath.Join(home, "bin", "m2.conf"), []byte(stockM2Conf), 0o600))
147 require.NoError(t, os.WriteFile(filepath.Join(home, "lib", "maven-core-3.9.12.jar"), nil, 0o600))
148 return filepath.Join(home, "bin", "mvn")
151// withSystemMavenRC points the launcher's fixed-path rc files at paths.
152func withSystemMavenRC(t *testing.T, paths ...string) {
153 t.Helper()
154 saved := mavenSystemRCFiles
155 mavenSystemRCFiles = paths
156 t.Cleanup(func() { mavenSystemRCFiles = saved })
159func TestMavenGlobalSettingsFile(t *testing.T) {
160 withSystemMavenRC(t)
161 mvn := fakeMavenInstall(t, t.TempDir())
162 install, err := filepath.EvalSymlinks(filepath.Dir(filepath.Dir(mvn)))
163 require.NoError(t, err)
165 t.Run("when -gs names it", func(t *testing.T) {
166 dir := t.TempDir()
167 require.NoError(t, os.WriteFile(filepath.Join(dir, "g.xml"), []byte("<settings/>"), 0o600))
168 for _, args := range [][]string{{"-gs", "g.xml", "verify"}, {"-gs=g.xml", "verify"}, {"--global-settings=g.xml", "verify"}} {
169 got, err := mavenGlobalSettingsFile(nil, dir, args, mvn)
170 require.NoError(t, err)
171 assert.Equal(t, filepath.Join(dir, "g.xml"), got, args)
172 }
174 got, err := mavenGlobalSettingsFile(nil, dir, []string{"-gsg.xml", "verify"}, mvn)
175 require.NoError(t, err)
176 assert.Equal(t, filepath.Join(install, "conf", "settings.xml"), got, "Maven rejects -gsFILE rather than reading it")
177 })
179 t.Run("when -gs names a file that doesn't exist", func(t *testing.T) {
180 _, err := mavenGlobalSettingsFile(nil, t.TempDir(), []string{"-gs", "typo.xml", "verify"}, mvn)
181 assert.Error(t, err, "Maven fails on it, so glab mustn't hand it an empty file instead")
182 })
184 t.Run("when MAVEN_ARGS or maven.config names it", func(t *testing.T) {
185 dir := t.TempDir()
186 global := filepath.Join(t.TempDir(), "g.xml")
187 require.NoError(t, os.WriteFile(global, []byte("<settings/>"), 0o600))
188 got, err := mavenGlobalSettingsFile([]string{"MAVEN_ARGS=-gs " + global}, dir, []string{"verify"}, mvn)
189 require.NoError(t, err)
190 assert.Equal(t, global, got)
192 require.NoError(t, os.MkdirAll(filepath.Join(dir, ".mvn"), 0o700))
193 require.NoError(t, os.WriteFile(filepath.Join(dir, ".mvn", "maven.config"), []byte("-gs\n"+global+"\n"), 0o600))
194 got, err = mavenGlobalSettingsFile(nil, dir, []string{"verify"}, mvn)
195 require.NoError(t, err)
196 assert.Equal(t, global, got)
197 })
199 t.Run("when it comes from the install mvn belongs to", func(t *testing.T) {
200 root := t.TempDir()
201 target := fakeMavenInstall(t, filepath.Join(root, "maven", "apache-maven-3.9.12"))
202 require.NoError(t, os.MkdirAll(filepath.Join(root, "bin"), 0o700))
203 link := filepath.Join(root, "bin", "mvn")
204 require.NoError(t, os.Symlink(target, link))
205 want, err := filepath.EvalSymlinks(filepath.Join(root, "maven", "apache-maven-3.9.12"))
206 require.NoError(t, err)
208 got, err := mavenGlobalSettingsFile(nil, t.TempDir(), []string{"verify"}, link)
210 require.NoError(t, err)
211 assert.Equal(t, filepath.Join(want, "conf", "settings.xml"), got, "the launcher resolves its own symlinks to find its install")
212 })
214 t.Run("when mvn is Homebrew's wrapper", func(t *testing.T) {
215 prefix := t.TempDir()
216 cellar := filepath.Join(prefix, "Cellar", "maven", "3.9.12")
217 fakeMavenInstall(t, filepath.Join(cellar, "libexec"))
218 require.NoError(t, os.MkdirAll(filepath.Join(cellar, "bin"), 0o700))
219 require.NoError(t, os.WriteFile(filepath.Join(cellar, "bin", "mvn"), []byte("#!/bin/bash\nexec libexec/bin/mvn \"$@\"\n"), 0o700))
220 require.NoError(t, os.MkdirAll(filepath.Join(prefix, "bin"), 0o700))
221 link := filepath.Join(prefix, "bin", "mvn")
222 require.NoError(t, os.Symlink(filepath.Join(cellar, "bin", "mvn"), link))
223 want, err := filepath.EvalSymlinks(filepath.Join(cellar, "libexec"))
224 require.NoError(t, err)
226 got, err := mavenGlobalSettingsFile(nil, t.TempDir(), []string{"verify"}, link)
227 require.NoError(t, err)
228 assert.Equal(t, filepath.Join(want, "conf", "settings.xml"), got, "Homebrew's wrapper runs the install in libexec")
230 require.NoError(t, os.MkdirAll(filepath.Join(prefix, "etc"), 0o700))
231 require.NoError(t, os.WriteFile(filepath.Join(prefix, "etc", "mavenrc"), []byte("MAVEN_ARGS=\"-gs /srv/g.xml\"\n"), 0o600))
232 _, err = mavenGlobalSettingsFile(nil, t.TempDir(), []string{"verify"}, link)
233 assert.Error(t, err, "Homebrew's launcher sources its own etc/mavenrc")
234 })
236 t.Run("when mvn is a later Maven 3", func(t *testing.T) {
237 later := t.TempDir()
238 mvnLater := fakeMavenInstall(t, later)
239 require.NoError(t, os.Rename(filepath.Join(later, "lib", "maven-core-3.9.12.jar"), filepath.Join(later, "lib", "maven-core-3.10.0.jar")))
240 laterHome, err := filepath.EvalSymlinks(later)
241 require.NoError(t, err)
243 got, err := mavenGlobalSettingsFile(nil, t.TempDir(), []string{"verify"}, mvnLater)
245 require.NoError(t, err)
246 assert.Equal(t, filepath.Join(laterHome, "conf", "settings.xml"), got)
247 })
249 t.Run("when mvn isn't Maven 3.9 or a later 3.x", func(t *testing.T) {
250 shim := filepath.Join(t.TempDir(), "mvn")
251 require.NoError(t, os.WriteFile(shim, []byte("#!/bin/sh\n"), 0o700))
252 _, err := mavenGlobalSettingsFile(nil, t.TempDir(), []string{"-gs", "/etc/g.xml", "verify"}, shim)
253 require.Error(t, err, "a shim or wrapper hides the install whose settings Maven reads")
255 _, err = mavenGlobalSettingsFile(nil, t.TempDir(), []string{"verify"}, filepath.Join(t.TempDir(), "mvn"))
256 require.Error(t, err, "mvn has gone")
258 maven4 := t.TempDir()
259 mvn4 := fakeMavenInstall(t, maven4)
260 for _, jar := range []string{"maven-core-4.0.0-rc-7.jar", "maven-core-4.9.0.jar"} {
261 require.NoError(t, os.RemoveAll(filepath.Join(maven4, "lib")))
262 require.NoError(t, os.MkdirAll(filepath.Join(maven4, "lib"), 0o700))
263 require.NoError(t, os.WriteFile(filepath.Join(maven4, "lib", jar), nil, 0o600))
264 _, err = mavenGlobalSettingsFile(nil, t.TempDir(), []string{"verify"}, mvn4)
265 require.Error(t, err, "Maven 4 also reads project and installation settings: %s", jar)
266 }
268 older := t.TempDir()
269 mvnOlder := fakeMavenInstall(t, older)
270 require.NoError(t, os.Rename(filepath.Join(older, "lib", "maven-core-3.9.12.jar"), filepath.Join(older, "lib", "maven-core-3.8.8.jar")))
271 _, err = mavenGlobalSettingsFile(nil, t.TempDir(), []string{"verify"}, mvnOlder)
272 require.Error(t, err, "the launcher only passes MAVEN_ARGS on from 3.9")
274 for _, m2 := range []string{"set maven.conf default /srv/conf\n", "set\tmaven.conf default /srv/conf\n"} {
275 moved := t.TempDir()
276 mvnMoved := fakeMavenInstall(t, moved)
277 require.NoError(t, os.WriteFile(filepath.Join(moved, "bin", "m2.conf"), []byte(m2), 0o600))
278 _, err = mavenGlobalSettingsFile(nil, t.TempDir(), []string{"verify"}, mvnMoved)
279 assert.Error(t, err, "bin/m2.conf can move the conf directory: %q", m2)
280 }
281 })
283 t.Run("when the launcher sources an rc file", func(t *testing.T) {
284 homeWithRC := func(t *testing.T, body string) string {
285 t.Helper()
286 home := t.TempDir()
287 require.NoError(t, os.WriteFile(filepath.Join(home, ".mavenrc"), []byte(body), 0o600))
288 return home
289 }
290 for _, body := range []string{
291 "MAVEN_ARGS=\"-gs /srv/g.xml\"\n",
292 "MAVEN_OPTS=\"$MAVEN_OPTS -Xmx1g\"\n",
293 ". /srv/more-rc\n",
294 "JAVA_HOME=$(/usr/libexec/java_home)\n",
295 "JAVA_HOME=`/usr/libexec/java_home`\n",
296 "JAVA_HOME=\"/usr/lib/jvm/`x`\"\n",
297 "JAVA_HOME=\"/usr/lib/jvm/\\\"\nMAVEN_OPTS=\" ;MAVEN_ARGS=-o; X=\"\n",
298 "JAVA_HOME=/usr/lib/jvm/java(21\n",
299 "JAVA_HOME=/usr/lib/jvm/java-21;MAVEN_ARGS=-o\n",
300 "JAVA_HOME=/usr/lib/jvm/java-21&&MAVEN_ARGS=-o\n",
301 "JAVA_HOME=/usr/lib/jvm/java-21|sh\n",
302 "JAVA_HOME=/usr/lib/jvm/java-21>/tmp/x\n",
303 "JAVA_HOME=(/usr/lib/jvm/java-21)\n",
304 "true; JAVA_HOME=/usr/lib/jvm/java-21\n",
305 "JAVA_HOME=/usr/lib/jvm/java-21; MAVEN_ARGS=-o\n",
306 "JAVA_HOME=/usr/lib/jvm/java-21 MAVEN_ARGS=-o\n",
307 "exportMAVEN_OPTS=-Xmx1g\n",
308 "MAVEN_OPTS='-Xmx2g -Dmaven.conf=/srv/conf'\n",
309 "MAVEN_OPTS=-Dmaven.conf=/srv/conf\n",
310 "MAVEN_OPTS=\"-Dmaven.conf=/srv/conf\"\n",
311 "export MAVEN_OPTS='-Dmaven.conf=/srv/conf'\n",
312 } {
313 _, err := mavenGlobalSettingsFile([]string{"HOME=" + homeWithRC(t, body)}, t.TempDir(), []string{"verify"}, mvn)
314 require.Error(t, err, body)
315 }
317 // Alpine's maven package ships this /etc/mavenrc.
318 alpine := filepath.Join(t.TempDir(), "mavenrc")
319 require.NoError(t, os.WriteFile(alpine, []byte("M2_HOME=\"/usr/share/java/maven-3\"\n"), 0o600))
320 withSystemMavenRC(t, alpine)
321 home := homeWithRC(t, "# local tweaks\n\nexport JAVA_HOME=/usr/lib/jvm/java-21\r\nMAVEN_OPTS='-Xmx2g -XX:+UseG1GC'\n")
322 got, err := mavenGlobalSettingsFile([]string{"HOME=" + home}, t.TempDir(), []string{"verify"}, mvn)
323 require.NoError(t, err)
324 assert.Equal(t, filepath.Join(install, "conf", "settings.xml"), got, "these rc files can't change the settings Maven reads")
326 withSystemMavenRC(t, filepath.Join(homeWithRC(t, "MAVEN_ARGS=-o\n"), ".mavenrc"))
327 _, err = mavenGlobalSettingsFile(nil, t.TempDir(), []string{"verify"}, mvn)
328 require.Error(t, err, "a system rc file counts too")
329 got, err = mavenGlobalSettingsFile([]string{"MAVEN_SKIP_RC=true"}, t.TempDir(), []string{"verify"}, mvn)
330 require.NoError(t, err)
331 assert.Equal(t, filepath.Join(install, "conf", "settings.xml"), got)
333 unreadable := filepath.Join(t.TempDir(), "mavenrc")
334 require.NoError(t, os.Mkdir(unreadable, 0o700))
335 withSystemMavenRC(t, unreadable)
336 _, err = mavenGlobalSettingsFile(nil, t.TempDir(), []string{"verify"}, mvn)
337 require.Error(t, err, "an rc file glab can't read could change anything")
338 })
340 t.Run("when the Windows launcher runs an rc file", func(t *testing.T) {
341 for _, name := range []string{"mavenrc_pre.bat", "mavenrc_pre.cmd"} {
342 profile := t.TempDir()
343 require.NoError(t, os.WriteFile(filepath.Join(profile, name), nil, 0o600))
344 _, err := mavenGlobalSettingsFile([]string{"USERPROFILE=" + profile}, t.TempDir(), []string{"verify"}, mvn)
345 require.Error(t, err, name)
346 }
347 got, err := mavenGlobalSettingsFile([]string{"USERPROFILE=" + t.TempDir()}, t.TempDir(), []string{"verify"}, mvn)
348 require.NoError(t, err)
349 assert.Equal(t, filepath.Join(install, "conf", "settings.xml"), got)
350 })
352 t.Run("when the launcher could pick another project directory", func(t *testing.T) {
353 for _, tc := range []struct {
354 environ []string
355 args []string
356 }{
357 {nil, []string{"-f", "other/pom.xml", "verify"}},
358 {nil, []string{"--file", "other", "verify"}},
359 {[]string{"MAVEN_BASEDIR=/srv/other"}, []string{"verify"}},
360 } {
361 _, err := mavenGlobalSettingsFile(tc.environ, t.TempDir(), tc.args, mvn)
362 assert.Error(t, err, "%v %v: that project's .mvn could name another -gs", tc.environ, tc.args)
363 }
364 })
366 t.Run("when an argument is quoted", func(t *testing.T) {
367 _, err := mavenGlobalSettingsFile([]string{`MAVEN_ARGS="-gs=/srv/g.xml"`}, t.TempDir(), []string{"verify"}, mvn)
368 require.Error(t, err, "Maven strips the quotes and reads -gs")
370 dir := t.TempDir()
371 require.NoError(t, os.MkdirAll(filepath.Join(dir, ".mvn"), 0o700))
372 require.NoError(t, os.WriteFile(filepath.Join(dir, ".mvn", "maven.config"), []byte(`'-gs=/srv/g.xml'`+"\n"), 0o600))
373 _, err = mavenGlobalSettingsFile(nil, dir, []string{"verify"}, mvn)
374 assert.Error(t, err)
375 })
377 t.Run("when the caller moves maven.conf", func(t *testing.T) {
378 for _, tc := range []struct {
379 environ []string
380 args []string
381 }{
382 {[]string{"MAVEN_OPTS=-Dmaven.conf=/srv/conf"}, nil},
383 {[]string{"MAVEN_DEBUG_OPTS=-Dmaven.conf=/srv/conf"}, nil},
384 {[]string{"JAVA_TOOL_OPTIONS=-Dmaven.conf=/srv/conf"}, nil},
385 {[]string{"JDK_JAVA_OPTIONS=-Dmaven.conf=/srv/conf"}, nil},
386 {[]string{"_JAVA_OPTIONS=-Dmaven.conf=/srv/conf"}, nil},
387 {[]string{"MAVEN_ARGS=-Dmaven.conf=/srv/conf"}, nil},
388 {nil, []string{"-D", "maven.conf=/srv/conf"}},
389 {nil, []string{"--define=maven.conf=/srv/conf"}},
390 {[]string{"MAVEN_OPTS=-Dmaven.conf"}, nil},
391 {[]string{`JAVA_TOOL_OPTIONS=-D"maven.conf=/srv/conf"`}, nil},
392 {[]string{`JDK_JAVA_OPTIONS="-Dmaven.conf=/srv/conf"`}, nil},
393 } {
394 _, err := mavenGlobalSettingsFile(tc.environ, t.TempDir(), append(tc.args, "verify"), mvn)
395 require.Error(t, err, "%v %v: glab's -gs would override the caller's conf", tc.environ, tc.args)
396 }
398 dir := t.TempDir()
399 require.NoError(t, os.MkdirAll(filepath.Join(dir, ".mvn"), 0o700))
400 require.NoError(t, os.WriteFile(filepath.Join(dir, ".mvn", "jvm.config"), []byte("-Xmx1g -Dmaven.conf=/srv/conf\n"), 0o600))
401 _, err := mavenGlobalSettingsFile(nil, filepath.Join(dir, "module"), []string{"verify"}, mvn)
402 require.Error(t, err, ".mvn/jvm.config is passed to the JVM")
404 global := filepath.Join(t.TempDir(), "g.xml")
405 require.NoError(t, os.WriteFile(global, []byte("<settings/>"), 0o600))
406 got, err := mavenGlobalSettingsFile([]string{"MAVEN_OPTS=-Dmaven.conf=/srv/conf"}, t.TempDir(), []string{"-gs", global, "verify"}, mvn)
407 require.NoError(t, err)
408 assert.Equal(t, global, got, "an explicit -gs wins over maven.conf anyway")
409 })
411 t.Run("when an option only mentions maven.conf", func(t *testing.T) {
412 dir := t.TempDir()
413 require.NoError(t, os.MkdirAll(filepath.Join(dir, ".mvn"), 0o700))
414 require.NoError(t, os.WriteFile(filepath.Join(dir, ".mvn", "maven.config"), []byte("# -Dmaven.conf=/srv/conf\n-B\n"), 0o600))
416 got, err := mavenGlobalSettingsFile([]string{"MAVEN_OPTS=-Dtest=org.acme.maven.conf.FooTest"}, dir, []string{"verify"}, mvn)
418 require.NoError(t, err)
419 assert.Equal(t, filepath.Join(install, "conf", "settings.xml"), got, "Maven skips # lines in maven.config, and a value that merely contains maven.conf sets nothing")
420 })
422 t.Run("when a comment sits between -gs and its value in maven.config", func(t *testing.T) {
423 dir := t.TempDir()
424 global := filepath.Join(t.TempDir(), "g.xml")
425 require.NoError(t, os.WriteFile(global, []byte("<settings/>"), 0o600))
426 require.NoError(t, os.MkdirAll(filepath.Join(dir, ".mvn"), 0o700))
427 require.NoError(t, os.WriteFile(filepath.Join(dir, ".mvn", "maven.config"), []byte("-gs\n# the team's settings\n"+global+"\n"), 0o600))
429 got, err := mavenGlobalSettingsFile(nil, dir, []string{"verify"}, mvn)
431 require.NoError(t, err)
432 assert.Equal(t, global, got, "Maven skips the comment and takes the next line as the value")
433 })
435 t.Run("when other JVM options would move the global settings", func(t *testing.T) {
436 environ := []string{"_JAVA_OPTIONS=-Dclassworlds.conf=/srv/m2.conf -Dmaven.multiModuleProjectDirectory=/srv/other -Duser.dir=/srv"}
438 got, err := mavenGlobalSettingsFile(environ, t.TempDir(), []string{"-Dnote=see-.mvn/maven.config", "verify"}, mvn)
440 require.NoError(t, err)
441 assert.Equal(t, filepath.Join(install, "conf", "settings.xml"), got, "glab passes this file as -gs, which Maven reads first")
442 })
444 t.Run("when -gs is empty or there is no mvn binary", func(t *testing.T) {
445 _, err := mavenGlobalSettingsFile(nil, t.TempDir(), []string{"-gs=", "verify"}, mvn)
446 require.Error(t, err)
447 _, err = mavenGlobalSettingsFile(nil, t.TempDir(), []string{"-gs", "/etc/g.xml", "verify"}, "")
448 assert.Error(t, err)
449 })
452// TestMavenManagerKnownMirrors goes through the manager, since the matcher
453// Run hands the proxy is taken before CATrustEnviron reads the settings.
454func TestMavenManagerKnownMirrors(t *testing.T) {
455 parentPOM := httptest.NewRequest(http.MethodGet, "https://nexus.example.com/repository/public/org/apache/logging/log4j/log4j/2.24.3/log4j-2.24.3.pom", http.NoBody)
457 // The last run's MAVEN_ARGS, manager, CA path and mvn binary.
458 var (
459 mavenArgs []string
460 lastM PackageManager
461 lastCA string
462 lastMvn string
463 )
464 run := func(t *testing.T, globalXML []byte, args ...string) []string {
465 t.Helper()
466 for _, name := range []string{"MAVEN_ARGS", "MAVEN_BASEDIR", "MAVEN_OPTS"} {
467 t.Setenv(name, "")
468 }
469 t.Setenv("HOME", t.TempDir())
470 t.Setenv("USERPROFILE", t.TempDir())
471 withSystemMavenRC(t)
472 t.Chdir(t.TempDir())
473 install := t.TempDir()
474 mvn := fakeMavenInstall(t, install)
475 if globalXML != nil {
476 require.NoError(t, os.WriteFile(filepath.Join(install, "conf", "settings.xml"), globalXML, 0o600))
477 }
479 m := Maven()
480 mm, ok := m.(*mavenManager)
481 require.True(t, ok)
482 mm.lookPath = func(string) (string, error) { return mvn, nil }
483 matcher := m.Matcher()
484 mm.SetArgs(append(args, "-Duser.home="+t.TempDir(), "verify"))
485 m.Environment("http://127.0.0.1:52999")
486 mavenArgs, lastM, lastCA, lastMvn = nil, m, filepath.Join(t.TempDir(), "ca.pem"), mvn
487 for _, kv := range m.CATrustEnviron(lastCA) {
488 if v, ok := strings.CutPrefix(kv, "MAVEN_ARGS="); ok {
489 mavenArgs = strings.Fields(v)
490 }
491 }
493 match := matcher.Match(parentPOM)
494 names := []string{match.Coordinate.Name}
495 for _, c := range match.Alternates {
496 names = append(names, c.Name)
497 }
498 return names
499 }
500 // pinned returns the file the last run passed Maven as -gs, read back.
501 pinned := func(t *testing.T) string {
502 t.Helper()
503 require.GreaterOrEqual(t, len(mavenArgs), 4, "MAVEN_ARGS %q", mavenArgs)
504 require.Equal(t, "-s", mavenArgs[0])
505 require.Equal(t, "-gs", mavenArgs[2], "glab's -s and -gs come first, so Maven takes them")
506 info, err := os.Stat(mavenArgs[3])
507 require.NoError(t, err)
508 assert.Equal(t, os.FileMode(0o600), info.Mode().Perm(), "the copy can hold credentials")
509 raw, err := os.ReadFile(mavenArgs[3])
510 require.NoError(t, err)
511 return string(raw)
512 }
514 t.Run("when the caller's settings have a catch-all mirror", func(t *testing.T) {
515 user := writeUserSettings(t, string(mirrorsXML(mirrorXML("corp", "*", "https://nexus.example.com/repository/public/"))))
517 assert.Equal(t, []string{"org.apache.logging.log4j:log4j"}, run(t, nil, "-s", user))
518 assert.Equal(t, "<settings/>\n", pinned(t), "with no global settings, Maven must read none")
519 })
521 t.Run("when the install's global settings have it", func(t *testing.T) {
522 global := mirrorsXML(mirrorXML("corp", "*", "https://nexus.example.com/repository/public/"))
523 t.Setenv("_JAVA_OPTIONS", "-Dclassworlds.conf=/srv/m2.conf -Dmaven.multiModuleProjectDirectory=/srv/other")
525 assert.Equal(t, []string{"org.apache.logging.log4j:log4j"}, run(t, global))
526 assert.Equal(t, string(global), pinned(t), "Maven reads the global settings glab checked, whatever the JVM options say")
528 lastM.CleanupCAFiles(lastCA)
529 assert.NoFileExists(t, mavenArgs[3])
530 })
532 t.Run("when glab can't write the copy for -gs", func(t *testing.T) {
533 run(t, mirrorsXML(mirrorXML("corp", "*", "https://nexus.example.com/repository/public/")))
534 m := Maven()
535 mm, ok := m.(*mavenManager)
536 require.True(t, ok)
537 mm.lookPath = func(string) (string, error) { return lastMvn, nil }
538 mm.SetArgs([]string{"-Duser.home=" + t.TempDir(), "verify"})
539 matcher := m.Matcher()
541 path, ok := mm.pinGlobalSettings(nil, filepath.Join(t.TempDir(), "missing", "global-settings.xml"))
543 assert.False(t, ok)
544 assert.Empty(t, path)
545 assert.NotEmpty(t, matcher.Match(parentPOM).Alternates, "without the copy Maven might read other mirrors, so glab keeps guessing")
546 })
548 t.Run("when the catch-all's URL comes from an environment variable", func(t *testing.T) {
549 t.Setenv("NEXUS_URL", "https://nexus.example.com/repository/public/")
550 global := mirrorsXML(mirrorXML("corp", "*", "${env.NEXUS_URL}"))
552 assert.Equal(t, []string{"org.apache.logging.log4j:log4j"}, run(t, global))
553 assert.Contains(t, pinned(t), "<url>https://nexus.example.com/repository/public/</url>", "Maven must fetch from the URL glab matches under")
554 })
556 t.Run("when the caller's catch-all URL comes from an environment variable", func(t *testing.T) {
557 t.Setenv("NEXUS_URL", "https://nexus.example.com/repository/public/")
558 user := writeUserSettings(t, string(mirrorsXML(mirrorXML("corp", "*", "${env.NEXUS_URL}"))))
560 assert.Equal(t, []string{"org.apache.logging.log4j:log4j"}, run(t, nil, "-s", user))
561 })
563 t.Run("when -gs names the settings with it", func(t *testing.T) {
564 global := writeUserSettings(t, string(mirrorsXML(mirrorXML("corp", "*", "https://nexus.example.com/repository/public/"))))
566 assert.Equal(t, []string{"org.apache.logging.log4j:log4j"}, run(t, nil, "-gs", global))
567 })
569 t.Run("when the only mirror isn't a catch-all", func(t *testing.T) {
570 user := writeUserSettings(t, string(mirrorsXML(mirrorXML("c", "central", "https://nexus.example.com/repository/public/"))))
572 assert.Contains(t, run(t, nil, "-s", user), "log4j:log4j", "without a catch-all the prefix is still guessed")
573 assert.NotContains(t, mavenArgs, "-gs", "glab leaves the global settings alone when it guesses")
574 })
576 t.Run("when glab can't use the caller's settings", func(t *testing.T) {
577 // A file the merge can't parse makes glab fall back to its own
578 // settings, so Maven never sees the caller's catch-all.
579 user := writeUserSettings(t, "<settings>&bogus;"+string(mirrorsXML(mirrorXML("corp", "*", "https://nexus.example.com/repository/public/")))[len("<settings xmlns=\"http://maven.apache.org/SETTINGS/1.0.0\">"):])
581 assert.Contains(t, run(t, nil, "-s", user), "log4j:log4j")
582 })
584 t.Run("when mvn can't be found", func(t *testing.T) {
585 t.Setenv("MAVEN_ARGS", "")
586 t.Chdir(t.TempDir())
587 user := writeUserSettings(t, string(mirrorsXML(mirrorXML("corp", "*", "https://nexus.example.com/repository/public/"))))
588 m := Maven()
589 mm, ok := m.(*mavenManager)
590 require.True(t, ok)
591 mm.lookPath = func(string) (string, error) { return "", errors.New("not found") }
592 matcher := m.Matcher()
593 mm.SetArgs([]string{"-s", user, "-Duser.home=" + t.TempDir(), "verify"})
594 m.Environment("http://127.0.0.1:52999")
595 m.CATrustEnviron(filepath.Join(t.TempDir(), "ca.pem"))
597 assert.NotEmpty(t, matcher.Match(parentPOM).Alternates, "unknown global settings could hold a mirror that wins for some repository")
598 })
601func TestMavenSettingsErrorKeepsTheFileOut(t *testing.T) {
602 dec := xml.NewDecoder(strings.NewReader("<settings>\n<password>&hunter2;</password></settings>"))
603 var err error
604 for err == nil {
605 _, err = dec.Token()
606 }
607 require.Contains(t, err.Error(), "hunter2", "the decoder quotes the file")
609 assert.Equal(t, "XML syntax error on line 2", mavenSettingsError(fmt.Errorf("merge: %w", err)))
610 assert.Equal(t, "no <settings> element", mavenSettingsError(errors.New("no <settings> element")))
Diagnostics7 git calls · 403 ms
CallStatusSizeTime0403 ms
discover200185 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=185
git.server.agent=git/2.56.g1891de4-Linux
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch server-option object-format
git.server.fetch=shallow wait-for-done filter
git.protocol.version=2
git.pkt.frames=9
git.pkt.data=7
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=185
git.pkt.payload.max=35
ls-refs20058 KiB193 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=186
git.response.bytes=59849
git.response.cache=EXPIRED
git.response.duration_ms=193
git.protocol.version=2
git.pkt.frames=731
git.pkt.data=730
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=59849
git.pkt.payload.max=143
git.ls_refs.count=730
git.ls_refs.head=refs/heads/main
fetchtree:0 · deepen 1020032 KiB · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=32926
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=22
git.pkt.data=20
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=32926
git.pkt.payload.max=32046
git.sideband.band1.bytes=32046
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=80
git.pack.bytes=32046
git.pack.ofs_delta=36
git.pack.ref_delta=0
git.pack.chain.max=2
git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91
git.pack.full=44
Open pack map
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit4 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=4
git.response.bytes=4273
git.response.cache=HIT
git.response.duration_ms=4
git.fetch.filter=combine:blob:none+tree:2
git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9
git.fetch.haves.count=0
git.fetch.deepen=1
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=7
git.pkt.data=5
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=4273
git.pkt.payload.max=4173
git.sideband.band1.bytes=4173
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=11
git.pack.bytes=4173
git.fetch.wide.objects=11
git.fetch.wide.extra_bytes=3930
git.fetch.wide.blobs=0
fetchtree:0200361 B · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=361
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=506cba622ceda1473ee3cde63969809c144b7247
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=361
git.pkt.payload.max=334
git.sideband.band1.bytes=334
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=334
git.pack.trailer=26d32585a3a474717e00a318584ccd16918c9d32
Open pack map
fetchtree:02001.3 KiB · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=1327
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=2758711b27b3e124482ce287b5df86092bb20d62
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=1327
git.pkt.payload.max=1300
git.sideband.band1.bytes=1300
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=1300
git.pack.trailer=c83fc6004a9a1360845513c0fb16272b5c14a3e4
Open pack map
fetch2009.4 KiB201 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=200
git.response.bytes=9611
git.response.cache=MISS
git.response.duration_ms=201
git.fetch.wants=eb7b92f4b8e25f78258f8f11ddcb46d87743e65c
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=9611
git.pkt.payload.max=9584
git.sideband.band1.bytes=9584
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://gitlab.com/gitlab-org/cli
Ref
refs/heads/main
Commit
0dd7574dce9e385c5c30540e6c15657adc6bdce9
cf-ray
a5e1c060da956c75
Request
91585bd4…
Protocol
v2 · sha1
Agent
git/2.56.g1891de4-Linux
Filter
advertised
Fetch
shallow wait-for-done filter
Capabilities
agent ls-refs fetch server-option object-format