Trying out Java/Scala/Groovy artefacts on the fly

There are times when you need to try out a simple snippet using a Java/Scala/Groovy artefact published on Maven central or the corporate repository.
Groovy (with all its goodness) can help you just do that without requiring you to create a dummy Maven, Gradle or SBT project.
The key piece is Grape which is a "JAR dependency manager embedded into Groovy."

For example let's say you need to quickly test something with Eclipse JGit.
Assuming you have already installed Groovy (eg via sdkman.), drop into the terminal and type groovysh to enter, well, the Groovy shell.


// Import the Grape API we need - it's just a static method
groovy:000> import static groovy.grape.Grape.grab
===> static groovy.grape.Grape.grab

// Ask Grape to download the specified artefact and all its dependencies.
// You may find the details for your artefact in https://mvnrepository.com
groovy:000> grab(group: 'org.eclipse.jgit', module: 'org.eclipse.jgit', version: '5.10.0.202012080955-r')
===> null

// Let's import from the JGit
groovy:000> import org.eclipse.jgit.api.Git
===> static groovy.grape.Grape.grab, org.eclipse.jgit.api.Git

// Open a git repository. Assign the return value to variable `repo`.
groovy:000> repo = Git.open('~/src/github/spotless' as File)
===> Git[Repository[~/src/github/spotless/.git]]

// You get the list of completions if you type `repo.` and then press TAB.
groovy:000> repo.
add()               apply()             archive()           blame()             branchCreate()      branchDelete()      branchList()        branchRename()      checkout()
cherryPick()        clean()             close()             commit()            describe()          diff()              fetch()             gc()                log()
lsRemote()          merge()             nameRev()           notesAdd()          notesList()         notesRemove()       notesShow()         pull()              push()
rebase()            reflog()            remoteAdd()         remoteList()        remoteRemove()      remoteSetUrl()      reset()             revert()            rm()
stashApply()        stashCreate()       stashDrop()         stashList()         status()            submoduleAdd()      submoduleDeinit()   submoduleInit()     submoduleStatus()
submoduleSync()     submoduleUpdate()   tag()               tagDelete()         tagList()           repository

groovy:000> repo.remoteList()()[0].getURIs()[0]
===> git@github.com:diffplug/spotless.git

You can achieve the same results using groovyConsole which launches a Swing GUI instead of entering a REPL. However, I personally prefer groovysh as it evaluates each line after I press ENTER. It also offers completion-list which is a gift for quick exploratory hacks.

Comments

Popular posts from this blog

Variables in GNU Make: Simple and Recursive

Checkmate on Your Terms: A Personal Journey with Correspondence Chess

Firefox profiles: Quickly replicate your settings to any machine