Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: "djLint" integration (linter, formatter) #6

Merged
merged 1 commit into from
Sep 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 17 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,15 @@ django templates (htmldjango) extension for [coc.nvim](https://github.com/neocli

- Format
- by [DjHTML](https://github.com/rtts/djhtml) ("Django/Jinja" template indenter) | [DEMO](https://github.com/yaegassy/coc-htmldjango/pull/2)
- [Experimental] by [djLint](https://github.com/Riverside-Healthcare/djlint) (reformat HTML templates)
- [Experimental] Lint (default: `false`)
- by [djLint](https://github.com/Riverside-Healthcare/djlint) (Find common formatting issues)
- Hover | [DEMO](https://github.com/yaegassy/coc-htmldjango/pull/1)
- CodeAction | [DEMO](https://github.com/yaegassy/coc-htmldjango/pull/3)
- Snippets completion
- To use it, you need to install [coc-snippets](https://github.com/neoclide/coc-snippets).
- And set `snippets.loadFromExtensions` to true in "coc-settings.json"
- Built-in installer (DjHTML)

It is possible to use `coc-htmldjango` with filetype other than `htmldjango`.

Set `g:coc_filetype_map` in ".vimrc" or "init.vim".

**e.g. jinja html**:

```vim
let g:coc_filetype_map = {
\ 'jinja.html': 'htmldjango',
\ }
```
- Built-in installer (DjHTML, djLint)

## Install

Expand All @@ -41,17 +32,29 @@ let g:coc_filetype_map = {
Plug 'yaegassy/coc-htmldjango', {'do': 'yarn install --frozen-lockfile'}
```

**Recommended coc extension**:

- [coc-html](https://github.com/neoclide/coc-html)
- [coc-snippets](https://github.com/neoclide/coc-snippets).

## Configuration options for coc-htmldjango

- `htmldjango.enable`: Enable coc-htmldjango extension, default: `true`
- `htmldjango.builtin.pythonPath`: Python 3.x path (Absolute path) to be used for built-in install, default: `""`
- `htmldjango.formatting.provider`: Provider for formatting. Possible options include 'djhtml', 'djlint', and 'none', default: `"djhtml"`
- `htmldjango.djhtml.commandPath`: The custom path to the djhtml (Absolute path), default: `""`
- `htmldjango.djhtml.tabWidth`: Set tabwidth (--tabwidth), default: `4`
- `htmldjango.djlint.commandPath`: The custom path to the djlint (Absolute path), default: `""`
- `htmldjango.djlint.enable`: Enable djLint (diagnostics), default: `false`
- `htmldjango.djlint.lintOnOpen`: Lint file on opening, default: `true`
- `htmldjango.djlint.lintOnChange`: Lint file on change, default: `true`
- `htmldjango.djlint.lintOnSave`: Lint file on save, default: `true`

## Commands

- `htmldjango.builtin.installTools`
- `htmldjango.djhtml.format`
- `htmldjango.djlint.format`

## Code Actions

Expand All @@ -78,6 +81,7 @@ coc-htmldjango allows you to create an extension-only "venv" and install "djhtml

- [vscode-django/vscode-django](https://github.com/vscode-django/vscode-django)
- [rtts/djhtml](https://github.com/rtts/djhtml)
- [Riverside-Healthcare/djlint](https://github.com/Riverside-Healthcare/djlint)
- [Unibeautify/unibeautify](https://github.com/Unibeautify/unibeautify)
- [neoclide/coc-snippets](https://github.com/neoclide/coc-snippets)
- [neoclide/coc-html](https://github.com/neoclide/coc-html)
Expand Down
41 changes: 40 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"name": "coc-htmldjango",
"version": "0.5.2",
"djlintVersion": "0.4.0",
"djhtmlVersion": "1.4.9",
"description": "django templates (htmldjango) extension for coc.nvim. Provides formatter, snippets completion and more...",
"author": "yaegassy <yosstools@gmail.com>",
Expand Down Expand Up @@ -61,6 +62,14 @@
"onLanguage:htmldjango"
],
"contributes": {
"rootPatterns": [
{
"filetype": "htmldjango",
"patterns": [
"pyproject.toml"
]
}
],
"configuration": {
"type": "object",
"title": "coc-htmldjango configuration",
Expand All @@ -87,9 +96,10 @@
"htmldjango.formatting.provider": {
"type": "string",
"default": "djhtml",
"description": "Provider for formatting. Possible options include 'djhtml' and 'unibeautify'",
"description": "Provider for formatting. Possible options include 'djhtml' and 'djlint'",
"enum": [
"djhtml",
"djlint",
"unibeautify",
"none"
]
Expand All @@ -104,6 +114,31 @@
"default": 4,
"description": "Set tabwidth (--tabwidth)"
},
"htmldjango.djlint.commandPath": {
"type": "string",
"default": "",
"description": "The custom path to the djlint (Absolute path)."
},
"htmldjango.djlint.enableLint": {
"type": "boolean",
"default": false,
"description": "Enable djLint lint (diagnostics)"
},
"htmldjango.djlint.lintOnOpen": {
"type": "boolean",
"default": true,
"description": "Lint file on opening"
},
"htmldjango.djlint.lintOnChange": {
"type": "boolean",
"default": true,
"description": "Lint file on change"
},
"htmldjango.djlint.lintOnSave": {
"type": "boolean",
"default": true,
"description": "Lint file on save"
},
"htmldjango.unibeautify.brace_style": {
"type": "string",
"default": "collapse",
Expand Down Expand Up @@ -291,6 +326,10 @@
{
"command": "htmldjango.djhtml.format",
"title": "DjHTML format"
},
{
"command": "htmldjango.djlint.format",
"title": "djLint format"
}
],
"snippets": [
Expand Down
3 changes: 3 additions & 0 deletions src/constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@
* May be read from package.json
*/

// @ts-ignore
import { djlintVersion } from '../package.json';
// @ts-ignore
import { djhtmlVersion } from '../package.json';

export const SUPPORT_LANGUAGES = ['htmldjango'];

export const DJHTML_VERSION = djhtmlVersion;
export const DJLINT_VERSION = djlintVersion;
5 changes: 5 additions & 0 deletions src/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
} from 'coc.nvim';

import { doDjhtmlFormat } from './formatter/djhtml';
import { doDjlintFormat } from './formatter/djlint';
import { doUnibeautifyFormat } from './formatter/unibeautify';

export type FormatFuncType = (
Expand Down Expand Up @@ -52,6 +53,8 @@ class HtmlDjangoFormattingEditProvider implements DocumentFormattingEditProvider
formatterFunc = doUnibeautifyFormat;
} else if (formatter === 'djhtml') {
formatterFunc = doDjhtmlFormat;
} else if (formatter === 'djlint') {
formatterFunc = doDjlintFormat;
}
} else {
const extensionConfig = workspace.getConfiguration('htmldjango');
Expand All @@ -61,6 +64,8 @@ class HtmlDjangoFormattingEditProvider implements DocumentFormattingEditProvider
formatterFunc = doUnibeautifyFormat;
} else if (formattingProvider === 'djhtml') {
formatterFunc = doDjhtmlFormat;
} else if (formattingProvider === 'djlint') {
formatterFunc = doDjlintFormat;
}
}

Expand Down
99 changes: 99 additions & 0 deletions src/formatter/djlint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { ExtensionContext, OutputChannel, Range, TextDocument, Uri, workspace, window } from 'coc.nvim';

import cp from 'child_process';
import fs from 'fs';
import tmp from 'tmp';

import { SUPPORT_LANGUAGES } from '../constant';
import { resolveDjlintPath } from '../tool';

export async function doDjlintFormat(
context: ExtensionContext,
outputChannel: OutputChannel,
document: TextDocument,
range?: Range
): Promise<string> {
if (!SUPPORT_LANGUAGES.includes(document.languageId)) {
throw '"djlint" cannot run, not supported language';
}

const extensionConfig = workspace.getConfiguration('htmldjango');

const text = document.getText(range);
const fileName = Uri.parse(document.uri).fsPath;

let djlintPath = extensionConfig.get('djlint.commandPath', '');
djlintPath = resolveDjlintPath(context, djlintPath);
if (!djlintPath) {
window.showErrorMessage('Unable to find the "djlint" command.');
return text;
}

const args: string[] = [];
const cwd = Uri.file(workspace.root).fsPath;
// Use shell
const opts = { cwd, shell: true };

args.push('--reformat');

const tmpFile = tmp.fileSync();
fs.writeFileSync(tmpFile.name, text);

// ---- Output the command to be executed to channel log. ----
outputChannel.appendLine(`${'#'.repeat(10)} djlint (format)\n`);
outputChannel.appendLine(`Cwd: ${opts.cwd}`);
outputChannel.appendLine(`File: ${fileName}`);
outputChannel.appendLine(`Args: ${args.join(' ')}`);
outputChannel.appendLine(`Run: ${djlintPath} ${args.join(' ')} ${tmpFile.name}`);

return new Promise(function (resolve) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
cp.execFile(djlintPath, [...args, tmpFile.name], opts, function (error, stdout, stderr) {
let updateText: string;
const originalText = fs.readFileSync(tmpFile.name, 'utf-8');

if (error) {
if (error.code === 2 || error.code === 127) {
outputChannel.appendLine(`\n==== ${JSON.stringify(error)} ===\n`);
throw error;
}
}

if (stdout) {
outputChannel.appendLine(`\n==== STDOUT ===\n`);
outputChannel.appendLine(`${stdout}`);

const isSuccess = isSuccessFormat(stdout);
outputChannel.appendLine(`== success ==: ${isSuccess}\n`);
if (isSuccess) {
updateText = fs.readFileSync(tmpFile.name, 'utf-8');
} else {
updateText = originalText;
}
} else {
updateText = originalText;
outputChannel.appendLine('');
}

tmpFile.removeCallback();
resolve(updateText);
});
});
}

function isSuccessFormat(s: string) {
let flag = false;
const lines = s.split('\n');
const p = /^(?<num>\d+)\sfile was updated.$/;

for (const v of lines) {
const m = v.match(p);
if (m) {
if (Number(m.groups?.num) >= 1) {
flag = true;
}
}
}

return flag;
}
Loading