Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

android - Refactor maven block in gradle

I'm working on an android project, and have a number of custom repositories using the same credentials:

repositories {
  maven {
    url "<url1>"
    credentials {
      username = "<username>"
      password = "<password>"
    }
  }

  maven {
    url "<url2>"
    credentials {
      username = "<username>"
      password = "<password>"
    }
  }

}

Is there a way to define a method (block?) so that I can define the username and password once and not have to repeat it every time? I'd like to be able to do:

repositories {
  customMaven { url "<url1>"}
  customMaven { url "<url2>"}
}

Apologies if I'm using terms incorrectly here - gradle syntax is somewhat of a mystery to me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First answer provided by @ToYonos will work fine, but if you are looking for a solution based on a configuration block, you can use the method MavenArtifactRepository maven(Action<? super MavenArtifactRepository> action) from RepositoryHandler class (see here), as follows:

// a Closure that builds an Action for configuring a MavenArtifactRepository instance
def customMavenRepo = { url ->
    return new Action<MavenArtifactRepository>() {
        void execute(MavenArtifactRepository repo) {
            repo.setUrl(url)
            repo.credentials(new Action<PasswordCredentials>() {
                void execute(PasswordCredentials credentials) {
                    credentials.setUsername("<username>")
                    credentials.setPassword("<password>")
                }
            });
        }
    };
}

// usage
repositories {
    jcenter()
    maven customMavenRepo("http://company.com/repo1")
    maven customMavenRepo("http://company.com/repo2")
    maven customMavenRepo("http://company.com/repo3")
}

EDIT from comments below: solution will Closure would look as follow. I think the use of curry method (see Currying closure) is needed here, but maybe there are other ways to simplify...

// one closure with URL as parameter
ext.myCustomMavenClosure = { pUrl ->
    url pUrl
    credentials {
        username = "<username>"
        password = "<password>"
    }
}
// helper function to return a "curried" closure
Closure myCustomMaven (url){
    return myCustomMavenClosure.curry(url)
}

repositories {
    // use closure directly
    maven myCustomMavenClosure.curry ("http://mycompany.com/repo1")
    // or use helper method
    maven myCustomMaven("http://mycompany.com/repo2")
}    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...