Code Monkey home page Code Monkey logo

badsyntax / vscode-spotless-gradle Goto Github PK

View Code? Open in Web Editor NEW
15.0 4.0 6.0 2.87 MB

A VS Code extension to lint & format your source files using Spotless & Gradle.

Home Page: https://marketplace.visualstudio.com/items?itemName=richardwillis.vscode-spotless-gradle

License: MIT License

TypeScript 97.66% Java 0.72% Groovy 0.19% CSS 0.03% JavaScript 1.24% Less 0.03% SCSS 0.03% C 0.02% C++ 0.03% Python 0.02% Objective-C 0.02% Objective-C++ 0.02%
spotless gradle vscode-extension vscode gradle-tasks

vscode-spotless-gradle's Introduction

Spotless Gradle

Marketplace Version Visual Studio Marketplace Installs Build & Publish CodeQL GitHub bug issues

A VS Code extension to lint & format your code using Spotless (via Gradle).

Spotless Gradle Screencast

Features

  • Provides diagnostics to show invalid formatting (with quick fixes)
  • Provides a Spotless fixAll code action (Format on Save)
  • Provides a Spotless formatter (Format Document)
  • Supports all languages that Spotless supports

Requirements

Usage

Before using this extension, ensure you've configured Spotless correctly in your Gradle build file. (Run ./gradlew spotlessDiagnose to prepare & validate Spotless.)

Enabling Spotless

Spotless formatting & diagnostics are disabled by default. Change the settings to adjust this behavior:

{
  "[java]": {
    "spotlessGradle.format.enable": true,
    "spotlessGradle.diagnostics.enable": true
  }
}

Formatting

Format on save:

{
  "[java]": {
    "spotlessGradle.format.enable": true,
    "editor.codeActionsOnSave": {
      "source.fixAll.spotlessGradle": true
    }
  }
}

If there are multiple formatters for a language type, set Spotless to be the default:

{
  "[java]": {
    "spotlessGradle.format.enable": true,
    "editor.defaultFormatter": "richardwillis.vscode-spotless-gradle"
  }
}

Disable other formatters to improve the performance, for example:

{
  "[java]": {
    "spotlessGradle.format.enable": true,
    "files.trimTrailingWhitespace": false
  }
}

Typical Usage

As Spotless formatting is not a global feature, you should enable Spotless on a per-project basis, which is achieved by adding a .vscode/settings.json file to the root of the project

Enable for specific languages:

{
  "java.format.enabled": false,
  "[java]": {
    "files.trimTrailingWhitespace": false,
    "spotlessGradle.diagnostics.enable": true,
    "spotlessGradle.format.enable": true,
    "editor.defaultFormatter": "richardwillis.vscode-spotless-gradle",
    "editor.codeActionsOnSave": {
      "source.fixAll.spotlessGradle": true
    }
  },
  "[gradle]": {
    "files.trimTrailingWhitespace": false,
    "spotlessGradle.diagnostics.enable": true,
    "spotlessGradle.format.enable": true,
    "editor.defaultFormatter": "richardwillis.vscode-spotless-gradle",
    "editor.codeActionsOnSave": {
      "source.fixAll.spotlessGradle": true
    }
  }
}

Enable for all languages:

{
  "java.format.enabled": false,
  "files.trimTrailingWhitespace": false,
  "spotlessGradle.diagnostics.enable": true,
  "spotlessGradle.format.enable": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.spotlessGradle": true
  },
  "[java]": {
    "editor.defaultFormatter": "richardwillis.vscode-spotless-gradle"
  },
  "[gradle]": {
    "editor.defaultFormatter": "richardwillis.vscode-spotless-gradle"
  }
}

How it Works

This extension runs the spotlessApply Gradle task on the focused file using the Spotless IDE hook feature. Untitled/Unsaved files are ignored.

The vscode => Spotless interface is provided by the Gradle for Java extension.

馃憠 Architecture Overview

Troubleshooting

View logs by selecting Spotless Gradle and/or Gradle for Java in the output panel.

Support

Credits

Release Notes

See CHANGELOG.md.

License

See LICENSE.md.

vscode-spotless-gradle's People

Contributors

badsyntax avatar dependabot-preview[bot] avatar dependabot[bot] avatar forestaa avatar snyk-bot avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar

vscode-spotless-gradle's Issues

Wrong encoding results in file not being formatted

We have UTF-8 Java files containing Umlauts (盲, 枚, 眉, 脽). While gradle spotlessApply works reliably on those files, the vscode-spotless-gradle plugin doesn't. I guess the plugin does not parse the file content as UTF-8 but uses some default encoding (we use Microsoft Windows by the way).

Extension hangs when running diagnostics or formatting for files without spotless config

The extension by default will run on all languages that Spotless supports.

When running diagnostics/formatting on a supported language for which there's no configured Spotless formatter, the extension gets into an unrecoverable state with "Gradle: Tasl :spotlessApply SUCCESS" shown in the statusbar:

Screenshot 2020-10-18 at 11 40 27

The first time the call fails, the status is correctly reported to the output channel and the extension is still working. The extenion hangs on the second call to spotless.

Can't format Gradle files

I'm trying to format Gradle files, but I have this error.

There is no formatter for 'gradle' files installed.

image

How do we use this extension?

Unable to format document

I have a Gradle project that I would like to format using this extension. This is my build.gradle, with the spotless configuration at the end of the file.

When I run gradle spotlessApply outside of VSCode, Gradle is successful, and issues in the files are fixed.

When I run the spotlessApply task using the Gradle Tasks extension, it is successful and works.

When I format the document, though, the issues are not fixed. I get this notification in VSCode:
image
The following is logged to the Gradle Tasks output:

[info] Completed build: spotlessApply -PspotlessIdeHook=/home/koopa/Documents/Projects/Java/Robot/Robot2021/src/main/java/frc/robot/Robot.java -PspotlessIdeHookUseStdIn -PspotlessIdeHookUseStdOut --quiet

The following is logged to the Spotless Gradle output:

[info] Running spotlessApply on Robot.java
[error] Unable to apply formatting: No status received from Spotless

Some other notes:

  • If this is the first time I'm formatting since reloading VSCode, the notification goes away in a second.
  • When formatting for the second time, the notification does not seem to go away. It seems that the build hangs after the first attempt. When cancelling this task, the following is logged to Gradle Tasks:
[info] Cancel build: Cancel build requested
[info] Build cancelled: spotlessApply -PspotlessIdeHook=/home/koopa/Documents/Projects/Java/Robot/Robot2021/src/main/java/frc/robot/Robot.java -PspotlessIdeHookUseStdIn -PspotlessIdeHookUseStdOut --quiet: Could not execute build using Gradle distribution 'https://services.gradle.org/distributions/gradle-6.0.1-bin.zip'.
  • After cancelling the second format, it's inconsistent as to whether or not it hangs.
  • When manually running the command from the Gradle Tasks output, the issues in the code are not fixed.

OS: Arch Linux
Gradle Version: 6.0.1
Gradle Tasks Version: 3.5.2
Spotless Gradle Version: 1.1.3

Improve changelog workflow

I added a mergeability app to check for changelog changes but this breaks CI when dependabot sends dep updates. As we're using GitHub releases & release drafter we don't need to keep a separate changelog updated.

  • remove the mergability app
  • update CHANGELOG.md to link to the releases page

There is no formatter for 'java' files Installed

Getting this pop-up when trying to format Java files

image
  • VS Code version: 1.81.0-insider
  • Gradle version: 8.2.1
  • Java version: 17.0.5
  • Gradle for Java extension: v3.12.7

Spotless Settings in VS Code:

"java.format.enabled": false,
"files.trimTrailingWhitespace": false,
"spotlessGradle.diagnostics.enable": true,
"spotlessGradle.format.enable": true,
"editor.codeActionsOnSave": {
  "source.fixAll.spotlessGradle": true
},
"[java]": {
  "editor.defaultFormatter": "richardwillis.vscode-spotless-gradle"
},
"[kotlin]": {
  "editor.defaultFormatter": "richardwillis.vscode-spotless-gradle"
},
"[kotlinGradle]": {
  "editor.defaultFormatter": "richardwillis.vscode-spotless-gradle"
}

Sample Project: https://github.com/overfullstack/ds-algo
Spotless Config: https://github.com/overfullstack/ds-algo/blob/master/buildSrc/src/main/kotlin/ds-algo.root-conventions.gradle.kts#L26

spotless {
  lineEndings = PLATFORM_NATIVE
  kotlin {
    ktfmt().googleStyle()
    target("**/*.kt")
    trimTrailingWhitespace()
    endWithNewline()
    targetExclude("**/build/**", "**/.gradle/**", "**/generated/**")
  }
  kotlinGradle {
    ktfmt().googleStyle()
    target("**/*.gradle.kts")
    trimTrailingWhitespace()
    endWithNewline()
    targetExclude("**/build/**", "**/.gradle/**", "**/generated/**")
  }
  java {
    toggleOffOn()
    target("**/*.java")
    importOrder()
    removeUnusedImports()
    googleJavaFormat()
    trimTrailingWhitespace()
    indentWithSpaces(2)
    endWithNewline()
    targetExclude("**/build/**", "**/.gradle/**", "**/generated/**")
  }
  format("xml") {
    targetExclude("pom.xml")
    target("*.xml")
    eclipseWtp(XML)
  }
  format("documentation") {
    target("*.md", "*.adoc")
    trimTrailingWhitespace()
    indentWithSpaces(2)
    endWithNewline()
  }
}

This has a mix of both Kotlin and Java

  • ./gradlew spotlessDiagnose --no-configuration-cache succeeds and Spotless is setup correctly as ./gradlew spotlessApply works as expected

Issue with vscode-gradle 3.7.0

I just upgraded to vscode-gradle 3.7.0 to fix issue with using a local version of Gradle. However now I get the error: "Cannot activate the 'Spotless Gradle' extension because it depends on an unknown 'richardwillis.vscode-gradle' extension."

I think this should be an easy change to microsoft.vscode-gradle, but am unsure. Thank you!

EDIT: It appears that badsyntax has been working diligently on this issue to resolve it. Feel free to close out this issue once that's merged.

It works, but slow

Dear @badsyntax ,

I configured succesfully the extension for VSCODE under WIN10 and all the configuration about spotless was already there (because working on an open source project already existing).

I've disabled the "diagnose" and set just for "formatting" on both save or format document.
There aren't issue at all and the single file will be formatted properly, but it take 2-3 seconds to run "spotlessApply".

Too slow for me; there is something that i can do to improve or something that you can do to speed up?

My guess is that it will starts gradle every time (like it not use daemon) so there is a lot of overhead before really apply spotlessApply; or maybe spotlessApply is simply slow.

I must use (cause the project is open source and cannot be changed) gradle 4.4.1, spotless plugin 3.30, JDK 1.8, GoogleJavaFormat style.

Release 1.0

I've been using this extension for a while and due to the amount of installs I assume others have been BETA testing it. No has reported any issues, and I haven't found any issues with it, so I assume it's pretty stable and worthy of a 1.0.0 stable release. I don't see any reason for waiting any longer.

TODO:

  • Bump version
  • Review and update README

Detect if spotlessApply task exists

Don't run the task if it doesn't exist. Perhaps show a warning if it doesn't exist.

In contrast, do we need to wait for vscode-gradle to query the build before running the spotlessApply task? Probably, but worth exploring this as a potential performance improvement.

Add support for newly supported languages

Spotless 5.2.0 added support for black (python) and clang-format (c, c++, c#, objective-c, protobuf, javascript, and java). So might want to hook into those VS Code project types as well.

Use webpack to bundle files

Getting the following warning when publishing:

This extension consists of 147 files, out of which 116 are JavaScript files. 
For performance reasons, you should bundle your extension: https://aka.ms/vscode-bundle-extension . 
You should also exclude unnecessary files by adding them to your .vscodeignore: https://aka.ms/vscode-vscodeignore

No more Gradle tasks with Gradle extension

Hello,

Thanks for this nice extension 馃憤

It perfectly worked last weeks but not anymore recently.

The official VS Code Gradle for Java 3.10 crashes when enabling this extension (version 1.2).

The "Refresh gradle tasks" command goes into e.getDebuggable error.

Gradle for Java output :

[info] Gradle Version: 7.3.3
[info] Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.3.3/userguide/command_line_interface.html#sec:command_line_warnings

CONFIGURE SUCCESSFUL in 5s
[error] Unable to refresh tasks: e.getDebuggable is not a function

Gradle tasks works fine when spotless gradle extension disabled.

Tested on Windows and Ubuntu on basic empty gradle project with minimal Java extensions without any specific settings.

Any idea ?

Unable to get spotless for gradle to run via onsave in VSCode

Hi,

I'm attempting to get this extension running for a java project. I can run spotless via CLI using gradlew spotlessApply but when I try adding the following settings
"java.format.enabled": false, "files.trimTrailingWhitespace": false, "spotlessGradle.diagnostics.enable": true, "spotlessGradle.format.enable": true, "editor.codeActionsOnSave": { "source.fixAll.spotlessGradle": true }, "[java]": { "editor.defaultFormatter": "richardwillis.vscode-spotless-gradle", },
I'm not able to see any changes after save or any sort of output in the Gradle for Java plugins output. Any recommendations?

Create dependency version manager

While vscode-gradle matures, the public API and internals might change and break this extension. As there's no way to use the vscode extension architecture to specify dependency versions, this must be managed within the extension itself.

Create a feature to ensure compatibility between extension versions. If the versions don't match show an error message informing the user which version of vscode-gradle they need to install.

Show bad formatting on invalid documents

I'd like to be able to show the invalid formatting within the document, similar to how other linters work in vscode, for example (TypeScript, eslint & Prettier):

Screenshot 2020-10-12 at 15 31 15

This feature depends on:

  • can i run spotlessCheck on individual files? can i use the same stdin/stdout mechanism?
  • can i parse the output of spotlessCheck in such a way as to provide useful feedback?
    • i'd like to highlight the diff of the changes similar to the screenshot above
    • ideal data format would be: line, column, endLine, endColumn

I'll need to do this through a vscode language server.

Typical spotlessCheck output for reference:

> The following files had format violations:
      gradle-server/src/main/java/com/github/badsyntax/gradle/GradleBuildCancellation.java
          @@ -25,14 +25,12 @@
           路路}
           
           路路public路static路void路cancelBuild(String路cancellationKey)路throws路GradleCancellationException路{
          -路路路路if路(路路Strings.isNullOrEmpty(路cancellationKey))
          -路路路路路路路路{
          -路路路路路路路路路路路路路路路路路路路路路路路路throw路new路GradleCancellationException("No路cancellation路key路specified");
          +路路路路if路(Strings.isNullOrEmpty(cancellationKey))路{
          +路路路路路路throw路new路GradleCancellationException("No路cancellation路key路specified");
           路路路路}
           路路路路CancellationTokenSource路cancellationTokenSource路=路tokens.get(cancellationKey);
           路路路路if路(cancellationTokenSource路==路null)路{
           
          -
           路路路路路路throw路new路GradleCancellationException("Build路is路not路running路for路key:路"路+路cancellationKey);
           路路路路}路else路{
           
      gradle-server/src/main/java/com/github/badsyntax/gradle/GradleWrapper.java
          @@ -23,7 +23,7 @@
           路路路路路路if路(args.length路==路0)路{
           路路路路路路路路throw路new路GradleWrapperException("No路wrapper路args路supplied");
           路路路路路路}
          -路路路路路路路路路路路路路路路路路路路路路路Process路process路=路new路Process(projectRoot);
          +路路路路路路Process路process路=路new路Process(projectRoot);
           路路路路路路process.setUnixCommand(GRADLE_WRAPPER_UNIX);
           路路路路路路process.setWindowsCommand(GRADLE_WRAPPER_WINDOWS);
           路路路路路路process.exec(args);
  Run './gradlew :gradle-server:spotlessApply' to fix these violations.

cc @nedtwigg

Add supported languages in the extension manifest

Today this extension cannot be used property as a default formatter for languages it supports since the extension doesn't advertise it self as supporting those languages into vscode runtime.

This can be simply enabled by adding the following to contribution section of the extension manifest package.json file. Example support for java which I tested with

		"languages": [
			{
				"id": "java",
				"aliases": [
					"Java"
				],
				"extensions": [
					"java"
				]
			}
		]

Similar approaches in other formatter extensions

Configuration cache & compatibility checks

This is both a bug report and a feature request.

What we need to do is:

  • Determine the minimum supported version of Gradle & Spotless Grade Plugin and gather this information from vscode-gradle
  • Show a message to the user informing them of any incompatibility

This will require a change in vscode-gradle to surface build information (Gradle version and dependency versions). vscode-gradle already has this information, there's just no public API to access it.

cc @nedtwigg

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.