Giter Site home page Giter Site logo

gradle-completion's Introduction

gradle-completion

Bash and Zsh completion support for Gradle.

This provides fast tab completion for:

  • Gradle tasks for the current project and sub-projects
  • Gradle CLI switches (e.g. --parallel)
  • Common Gradle properties (e.g. -Dorg.gradle.debug)

It also handles custom default build files, so rootProject.buildFileName = 'build.gradle.kts' is supported.

See instructions for bash or for zsh, then consider optional additional configuration.

Here's a demo for the gradle project itself: Completion demo

Installation for Zsh 5.0+

Install via Homebrew

brew install gradle-completion

# Ensure /usr/local/share/zsh/site-functions is on $fpath. You should get a result from the following
echo $fpath | grep "/usr/local/share/zsh/site-functions"

Install as oh-my-zsh plugin

Download and place the plugin and completion script into your oh-my-zsh plugins directory.

git clone https://github.com/gradle/gradle-completion ~/.oh-my-zsh/plugins/gradle-completion

Add gradle-completion to the plugins array in your '.zshrc' file.

plugins+=(gradle-completion)

Install manually

Download and place _gradle on your $fpath. I recommend $HOME/.zsh/gradle-completion:

git clone https://github.com/gradle/gradle-completion ~/.zsh/gradle-completion

Add the following do your '.zshrc' file:

echo "\nfpath=($HOME/.zsh/gradle-completion \$fpath)" >> ~/.zshrc

Start a new terminal session. You may need to disable the gradle plugin for oh-my-zsh.

(Optional) Manual Completion Cache Initialization

Completion cache initialization happens the first time you invoke completion, and usually takes a few seconds, depending on the size of your project. You can manually initialize the cache and avoid interrupting your development mojo by running:

cd path/to/your-project
source ~/.zsh/gradle-completion/_gradle 1>&2 2>/dev/null; __gradle-completion-init

Installation for Bash 3.2+

Install via Homebrew

brew install gradle-completion

# Source completion scripts from bash-completion in your bash profile
echo '[[ -r "/usr/local/etc/profile.d/bash_completion.sh" ]] && . "/usr/local/etc/profile.d/bash_completion.sh"' >> ~/.bash_profile

# Load changes to bash profile
source ~/.bash_profile

Install manually

Download and place gradle-completion.bash in your bash_completion.d folder, usually /etc/bash_completion.d, /usr/local/etc/bash_completion.d, or $HOME/bash_completion.d:

mkdir $HOME/bash_completion.d
curl -LA gradle-completion https://edub.me/gradle-completion-bash -o $HOME/bash_completion.d/gradle-completion.bash

NOTE: Ensure bash-completion 1.2+ is installed using your favorite package manager or by following the bash-completion installation instructions.

Add the following to your .bash_profile (macOS) or .bashrc (Linux) file:

source $HOME/bash_completion.d/gradle-completion.bash

Start a new terminal session.

(Optional) Manual Completion Cache Initialization

Completion cache initialization happens the first time you invoke completion, and usually takes a few seconds, depending on the size of your project. You can manually initialize the cache and avoid interrupting your development mojo by running:

cd path/to/your-project
__gradle-completion-init

Additional Configuration

Excluding build scripts from UP-TO-DATE check

Tab completion checks known build scripts to see if they've been changed and refreshes the task cache if so. You can exclude build scripts from this check (and speed up completion) by specifying:

# Default is `"/(build|integTest|out)/"`
export GRADLE_COMPLETION_EXCLUDE_PATTERN="/(build|integTest|samples|smokeTest|testFixtures|templates|out|features)/"
# Essentially turn off checking for changed scripts
export GRADLE_COMPLETION_EXCLUDE_PATTERN="gradle"

Completion cache

One can manually (re)generate the completion cache by invoking __gradle-completion-init after the completion script has been sourced. This graciously avoids an unexpected cache build when invoking completion.

The build script cache is invalidated if any *.gradle or *.gradle.kts files change. However, these completion scripts do not search for new build scripts every time completion is invoked, because that would make completion ~20x slower (unless you have so really good ideas on this).

By default, the build script cache is invalidated every 3 weeks (30240 minutes). You can configure this value by exporting a new value for $GRADLE_CACHE_TTL_MINUTES:

export GRADLE_CACHE_TTL_MINUTES=$(expr 1440 \* number_of_days_you_want)

Implicit Tasks

Gradle allows you to access tasks of subprojects from the project root implicitly. For example, given these tasks:

:foo
:help
:bar:baz

You can execute gradle baz from the project root and it will execute :bar:baz.

gradle-completion will not tab complete these tasks by default because it adds a significant number of completion options, which may not be what you want and negatively impacts completion speed.

To allow completion of implicit tasks, set $GRADLE_COMPLETION_UNQUALIFIED_TASKS=true:

export GRADLE_COMPLETION_UNQUALIFIED_TASKS="true"

You may need to invalidate the cache using the cache config above or by executing touch build.gradle.

Troubleshooting

If zsh completion isn't working, first try checking your $fpath with echo $fpath.

zsh completion using ./gradlew may not work on Linux if you don't have . on your $PATH, so I recommend adding it in your ~/.zshrc file:

export PATH=".:$PATH"

HEADS UP: If you get an error 'parse error near `]]"', please upgrade zsh. zsh 5.0.5 has a bug in script parsing that is fixed as of zsh 5.0.8. See issues #4 and #7 for more details.

If zsh completion reports "Generating Gradle task cache..." every time, the zsh completion cache may be disabled. Enable it by adding the following to your ~/.zshrc file:

zstyle ':completion:*' use-cache on

Contributing

See the contributing guide.

Acknowledgements

Bash completion is inspired by Nolan Lawson's Gradle tab completion for bash.

Zsh completion is an improved version of zsh's built-in Gradle completion.

Current improvements over built-in support:

  • Subproject tasks are completed
  • Gradle CLI options are current as of Gradle 6.4
  • Common Gradle properties are completed
  • Handles default build file as specified in settings.gradle
  • ~20x faster completion speed for medium to large projects
  • Completion cache updates in the background after first invocation

gradle-completion's People

Contributors

aconstantin avatar alllex avatar big-guy avatar danielthomas avatar eriwen avatar franckrasolo avatar grossws avatar martenbohlin avatar nielsdoucet avatar pkubowicz avatar rnc avatar samoylenko avatar smac89 avatar tinder-ryantrontz avatar vampire avatar wosiu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gradle-completion's Issues

Support for Fish Shell

I've tried the tool in my Fish shell and it doesn't work. Are you thinking about adding support for Fish shell too?

Thank you in advance, the tool looks great!

Regenerate cache if empty

If an error occurred during cache generation, we may be left with an empty cache file.

If we detect this, we should regenerate instead of always showing no completions.

oh-my-zsh plugin

Wrap zsh completion script contents in a function and call it. Add docs similar to git-flow-completion.

Root project build tasks not completed

I'm not seeing completions for build, assemble etc in a root project that doesn't have language plugins, but subprojects that do (so they're implicitly available).

Completion on subprojects doesn't work as expected

Instead of completing on :<subproject>:<task> it completes on <subproject>:<task>.
Notice the missing : at the start.

Gradle seems to support both syntaxes (not sure when the one without leading colon was introduced), so it should complete in both situations.

Build cache in the background on first invocation

Building completion cache can takes quite some time on a large and complex project. Apart from improving performance (e.g. #16) it would be great if it happened in the background.

Today when one presses tab for the first time they see the message about building completion cache and cannot do anything else while this happens. It would be much better experience when you could could continue to type and run Gradle while cache was populating in the background.

Default subproject for implicit completion

The GRADLE_COMPLETION_UNQUALIFIED_TASKS option causes the completion script to go over all subprojects, potentially pulling in too many tasks. Android apps generally always use :app: for the main subproject, could another env var direct the script to autocomplete for that by default?

Task descriptions truncated after latest changes

Seeing this on gradle/gradle since I updated this morning:

wrapper:javadoc                                                      -- Generates
wrapper:model                                                        -- Displays
wrapper:parallelIntegTest                                            -- Runs
wrapper:processIntegTestResources                                    -- Processes
wrapper:processResources                                             -- Processes
wrapper:processTestResources                                         -- Processes
wrapper:projects                                                     -- Displays
wrapper:properties                                                   -- Displays
wrapper:sourceJar                                                    --
wrapper:tasks                                                        -- Displays
wrapper:test                                                         -- Runs
wrapper:testClasses                                                  -- Assembles
wrapper:uploadArchives                                               -- Uploads
wrapper:verifyTestFilesCleanup                                       --
wrapper:wrapperBuildReceiptResource                                  --
$gradle_installPath  1.10  2.14      API         Javadoc       as             configuration.  external              integTests  modules          resources.     such
&                    1.11  2.14.1    Checkstyle  Maven         as-is.         containing      fat                   into        multi-project    root           tasks
'archives'           1.12  2.2       CodeNarc    OS            automated      cross           file                  it          new              run            test
'daemon'             1.2   2.2.1     Dependency  Scala         belong         declared        file.                 it.         of               runnable       testFixtures
'embedded'           1.3   2.3       Eclipse     TestKit       belonging      depend          files                 jar         on               runtime        tests
'embeddedDaemon'     1.4   2.4       Gradle      Tooling       build          dependencies    files.                jmh         on.              sample         tests.
'forking'            1.5   2.5       Graph       [incubating]  build.         dependency      fixtures              large       outputs          scripts        that
'gradle'             1.6   2.6       Groovy      a             buildscript    dependent       for                   local       performance      settings       the
'gradle'.            1.7   2.7       Groovydoc   against       by             depends         forking               lots        performanceTest  single         this
'parallel'           1.8   2.8       IDEA        all           checks.        directory       from                  main        plenty           small          to
(IML)                1.9   2.9       IPR)        an            classes        directory.      full                  manifests   plug-in          smoke          unit
(IML,                2.0   3.0       IPR,        analysis      classes.       displayed       gradle-script-kotlin  match       produced         smokeTest      userguide
(IPR)                2.1   3.1       IWS)        and           classpath      distribution    help                  may         project          source         version
(IWS)                2.10  3.2       JDT         application   code.          distribution.   in                    message.    project.         source.        versions
(some                2.11  3.2.1     JVM         application.  compatibility  distributions   insight               minimal     projects         specific       with
1.0                  2.12  3.3       Java        archive       components     documentation   integ                 model       properties       sub-projects   workspace
1.1                  2.13  3.4-rc-1  Java9       artifacts     configuration  executer        integTest             module      repository.      subprojects).  wrapper

Looks like there's a problem parsing the task descriptions.

Eliminate overhead when caching many tasks in zsh

Generating zsh completion cache can be especially slow on builds with >10000 tasks. Commit fc1459e helps a lot, but I've tested that caching takes about 1 second per 1000 tasks. This is much too long and can likely be mostly eliminated.

AWK may give us significantly improved performance, though the implementation will be more complex for handling unqualified tasks.

Something like this is a start.

     echo $gradle_tasks_output | awk '/^([[:lower:]][[:alnum:][:punct:]]*)([[:space:]]-[[:space:]]([[:print:]]*))?/ {
        task_name = match($0, /^[[:lower:]][[:alnum:][:punct:]]*/)
        task_description = match($0, /[[:space:]]-[[:space:]][[:print:]]*$/)
        line = sprintf("%s  - %s", $task_name, $task_description)
        if ($task_name ~ ^[[:alnum:]:]+:[[:alnum:]]+) { sprintf(":%s", $line); subproject_tasks+=( "${BASH_REMATCH[2]}" ) }
        else root_tasks+=( "$task_name" )
    }'

Discoverability from Gradle

It would be great to make the completion plugin discoverable from Gradle. For example when you first run Gradle from bash or zsh, it could ask you whether you want to install completion as well. Then when you press "Y" it would download and install it.

Breaks file completion in bash

If trying to reference a file when completing a gradle command, tab-completion no longer works.

E.g. ./gradlew -I ../[tab] to find an init script does not work.

Tested with Gradle 4.0, Bash 3.2.57(1)-release, MacOS 10.12.5

completion does not work for gradle scripts using kotlin

given

  • gradle flie build.gradle.kts and
  • an empty settings.gradle.kts

with this configuration the completion does not detect the build file and does not show the tasks.

it works when i rename settings.gradle.kts to settings.gradle and
add an entry rootProject.buildFileName = "build.gradle.kts"

it would be nice if the completion logic also would detect the buildfile without that

Does not work nicely with custom build script names created by variables

The completion works fine if your root build script is either named build.gradle or its name is set via rootProject.buildFileName = '...' or rootProject.buildFileName = "..." (actually also rootProject.buildFileName = "...' and rootProject.buildFileName = '...", but those will not compile anyway) exactly like that.
You cannot use a variable for the name, you cannot leave out the spaces around the equals sign or add more, it has to be at the start of a line without any preceding whitespaces, and you cannot use other constructs to set the name that are perfectly legal. In my case I do it for all projects like this which of course also does not work:

def setBuildFileNameRecursively
setBuildFileNameRecursively = { it ->
   it.buildFileName = "${it.name}.gradle"
   it.children.each { setBuildFileNameRecursively it }
}
setBuildFileNameRecursively rootProject

It would be nice if the completion would not require some narrow range of modification options but simply work. Is it really necessary to determine the root project filename upfront? Can't you use -p instead of -b for the call and use the project dir as cache key instead of the build file?

Completion should group by common prefix

In my case, I have about 80 sub projects in folders

`./gradlew :src:' + complete

I expect is to list projects first and after that the actual :src: project tasks.

Currently, it shown like there are thousands of items, next the whole set is shown.
Also, it may play nice if I were able to select an item with TAB in the same way as it works for ZSH/oh-my-zsh

Error using in zsh

I get error when trying to use this script using zsh + oh-my-zsh.
Using commit 511ec3d

Ξ external/jenkins git:(master) ▶ gradle --
_gradle:83: parse error near `]]'
_gradle:83: parse error near `]]'
_gradle:83: parse error near `]]'

The lines I added to .zshrc

zstyle ':completion:*' use-cache on
export PATH=".:$PATH"
fpath=(/home/stalle/.zsh/gradle-completion $fpath)

Update installation instructions for bash to make it work on macOS Sierra

Current installation instructions for bash didn't work for me on macOS Sierra. It currently says to update.bashrc. I had to update .bash_profile to make it work. This article explains the difference between .bashrc and .bash_profile, and here's what it says about Mac OS X (which is likely to be the case for macOS Sierra too):

An exception to the terminal window guidelines is Mac OS X’s Terminal.app, which runs a login shell by default for each new terminal window, calling .bash_profile instead of .bashrc. Other GUI terminal emulators may do the same, but most tend not to.

Update completion cache in background

Typically changes that trigger a cache rebuild are very minor, I recommend we return completions from previous cache immediately and update it in the background.

We should notify user that the cache will be updated for the next use.

Completion within subprojects doesn't work

Completion within subprojects doesn't seem to be working for me.

For example:

  • :, tab results in ::
  • :subp, tab doesn't complete to :subproject:
  • :subproject:ta, tab completes to :subproject::subproject:task

The actual subproject and task have different names but this is the behavior that I'm observing.

I'm using gradle-completion 1.3, installed via brew, on bash.

Simplify bash installation steps with brew

Looks like bash-completion is already a dependency for gradle-completion so brew install gradle-completion should be enough (instead of brew install bash-completion gradle-completion as currently specified in the documentation.

It would be awesome if the step echo '[ -f $(brew --prefix)/etc/bash_completion ] && . $(brew --prefix)/etc/bash_completion' >> ~/.bash_profile could also be handled by the installation.

Last update broke completion in bash

It seems with the latest update, all of the module and task completions are broken in bash.
:mo gets completed to ::module
:module:ta gets completed to :module::module:task
These prevent further completion because of the presence of :: in all of these cases.

mo get completed correctly to module:, but then module:ta is broken again, resulting in module:module:task

Avoid generating cache multiple times in parallel

Invoking tab completion multiple times in a row while the completion cache is being updated will spawn multiple subprocesses.

Provide some way of avoiding re-generating caches when there's a cache generation process already running.

Breaks bash completion of SCP (and probably others)

Without gradle-completion sourced in my .bashrc, I can do tab completion with scp:
scp remote_server:.bash_
...
scp remote_server:.bash_history

With gradle-completion sourced, I get:
scp remote_server:.bash_
...
scp .bash_history

I believe it is because COMP_WORDBREAKS is modified at the start of the script, which could effect any bash_completion script that uses the ':' character. I commented out this line in gradle-completion.bash, and scp completion began working again.

command not found

./gradlew bash: _get_comp_words_by_ref: command not found
bash: _get_comp_words_by_ref: command not found
bash: _get_comp_words_by_ref: command not found

Provide gradle init type completion for bash

If I write gradle init -- and press tab it does not expand to expected gradle init --type. If I write it down gradle init --type= and press tab it does not provide hints like: java-library, groovy-library.

------------------------------------------------------------
Gradle 4.6
------------------------------------------------------------

Build time:   2018-02-28 13:36:36 UTC
Revision:     8fa6ce7945b640e6168488e4417f9bb96e4ab46c

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.9 compiled on February 2 2017
JVM:          1.8.0_162 (Oracle Corporation 25.162-b12)
OS:           Mac OS X 10.13.3 x86_64

--rerun-tasks autocompletion is broken

completion return --rerun-task instead of --rerun-tasks resulting in:

FAILURE: Build failed with an exception.

* What went wrong:
Problem configuring task :agent-core:dependencies from command line.
> Unknown command-line option '--rerun-task'.

add support for uppercase subprojects

Hi,
it refuses to complete subprojects starting with an uppercase letter, e.g.
$ gradle :MySubproje...
In the project I am working, the names are fixed and renaming to lowercase is not an option.

_gradle:14: parse error near `]]'

Hi, I'm getting some cryptic error trying to use completion in zsh:

› gradle 
_gradle:14: parse error near `]]'
› zsh --version
zsh 5.0.5 (x86_64-suse-linux-gnu)

It seems to be valid check there, what may be a problem?

_gradle_caching_policy() {
     [[ ! $(find $1 -mmin -$cache_ttl_mins 2>/dev/null) ]]                                                                                                                                                                                
}

Arguments completion for standard tasks

Now completion doesn't for arguments of tasks.
For example, default task wrapper has arguments --gradle-version and --distribution-type, but autocompletion doesn't work for them.
Maybe it's a bigger problem: how to pass parameters to task using cli arguments without -D and -P and still be discoverable by a user, but anyway, standard tasks should have own argument completion lists.

Completion doesn't work for some projects

I installed version 1.3 for bash and it works for the first project I tried it on. After I navigated to another Gradle project the completion doesn't work. For example when I type ./gradlew bu, tab it completes to ./gradlew buildEnvironment despite build task being present.

autocomplete failed

Dear all,
after I using settings for build cache server, I've got following issue:

$ __gradle-completion-init 
 (Building completion cache. Please wait)
FAILURE: Build failed with an exception.

* Where:
Script '/path_of_project/buildCacheSettings.gradle' line: 3

* What went wrong:
A problem occurred evaluating script.
> Could not find method buildCache() for arguments [buildCacheSettings_6652z6kngfw6pr3eb8g2zfo4t$_run_closure1@4aac85fa] on settings 'rootProjectName' of type org.gradle.initialization.DefaultSettings.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

all other gradle comands work properly, no issue. But without gradle autocomplete is hard to tip all those long command :(

My setting is following:

  1. Gradle version: 4.0
  2. Java 8
  3. Linux Debian
  4. settings.gradle

apply from: "$rootProject.projectDir/buildCacheSettings.gradle"

  1. buildCacheSettings.gradle

ext.isCiServer = System.getenv().containsKey('CI')
buildCache {
local {
enabled = !isCiServer
}
remote(HttpBuildCache) {
url = System.getProperty('cache.url', 'http://private-buildcache-server')
credentials {
username = '*'
password = '
'
}
push = isCiServer
}
}

Any idea where the issue?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.