3131import javax .xml .xpath .XPathFactory ;
3232
3333import org .gradle .api .artifacts .repositories .MavenArtifactRepository ;
34+ import org .gradle .api .artifacts .repositories .PasswordCredentials ;
35+ import org .gradle .api .credentials .Credentials ;
36+ import org .gradle .internal .artifacts .repositories .AuthenticationSupportedInternal ;
3437import org .w3c .dom .Document ;
3538import org .w3c .dom .NodeList ;
3639import org .xml .sax .InputSource ;
@@ -83,9 +86,10 @@ private Set<String> resolveVersions(String groupId, String artifactId, MavenArti
8386 .toUri ();
8487 try {
8588 HttpHeaders headers = new HttpHeaders ();
86- String username = repository .getCredentials ().getUsername ();
89+ PasswordCredentials credentials = credentialsOf (repository );
90+ String username = (credentials != null ) ? credentials .getUsername () : null ;
8791 if (username != null ) {
88- headers .setBasicAuth (username , repository . getCredentials () .getPassword ());
92+ headers .setBasicAuth (username , credentials .getPassword ());
8993 }
9094 HttpEntity <Void > request = new HttpEntity <>(headers );
9195 String metadata = this .rest .exchange (url , HttpMethod .GET , request , String .class ).getBody ();
@@ -112,4 +116,25 @@ private Set<String> resolveVersions(String groupId, String artifactId, MavenArti
112116 return versions ;
113117 }
114118
119+ /**
120+ * Retrives the configured credentials of the given {@code repository}. We cannot use
121+ * {@link MavenArtifactRepository#getCredentials()} as, if the repository has no
122+ * credentials, it has the unwanted side-effect of assigning an empty set of username
123+ * and password credentials to the repository which may cause subsequent "Username
124+ * must not be null!" failures.
125+ * @param repository the repository that is the source of the credentials
126+ * @return the configured password credentials or {@code null}
127+ */
128+ private PasswordCredentials credentialsOf (MavenArtifactRepository repository ) {
129+ Credentials credentials = ((AuthenticationSupportedInternal ) repository ).getConfiguredCredentials ().getOrNull ();
130+ if (credentials != null ) {
131+ if (credentials instanceof PasswordCredentials passwordCredentials ) {
132+ return passwordCredentials ;
133+ }
134+ throw new IllegalStateException ("Repository '%s (%s)' has credentials '%s' that are not PasswordCredentials"
135+ .formatted (repository .getName (), repository .getUrl (), credentials ));
136+ }
137+ return null ;
138+ }
139+
115140}
0 commit comments