From c709efd658dba328816cc30544ef37e076a52a3d Mon Sep 17 00:00:00 2001 From: Christopher Pickering Date: Fri, 8 Jul 2022 11:06:01 -0500 Subject: [PATCH] feat(linter): added per-file-ignores as a config option for linter rules closes #107 --- docs/package-lock.json | 12 +- docs/src/_data/configuration.json | 326 ++++++++++++++ docs/src/_includes/foot.njk | 2 +- docs/src/_utils/scripts.11ty.js | 6 +- docs/src/docs/configuration.md | 405 +----------------- docs/src/docs/getting-started.md | 2 + docs/src/fr/docs/configuration.md | 404 +---------------- docs/src/fr/docs/getting-started.md | 2 + docs/src/ru/docs/configuration.md | 403 +---------------- docs/src/ru/docs/getting-started.md | 2 + docs/src/static/css/site.scss | 4 + docs/src/static/js/tabs.js | 34 ++ package-lock.json | 4 +- src/djlint/lint.py | 10 + src/djlint/settings.py | 2 + .../test_per_file_ignores/__init__.py | 0 .../test_per_file_ignores/html.html | 2 + .../test_per_file_ignores/pyproject.toml | 2 + .../test_per_file_ignores/test_config.py | 25 ++ 19 files changed, 483 insertions(+), 1164 deletions(-) create mode 100644 docs/src/_data/configuration.json create mode 100644 docs/src/static/js/tabs.js create mode 100644 tests/test_config/test_per_file_ignores/__init__.py create mode 100644 tests/test_config/test_per_file_ignores/html.html create mode 100644 tests/test_config/test_per_file_ignores/pyproject.toml create mode 100644 tests/test_config/test_per_file_ignores/test_config.py diff --git a/docs/package-lock.json b/docs/package-lock.json index cfeb1b6e..8898c759 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -3509,9 +3509,9 @@ } }, "node_modules/domelementtype": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.2.0.tgz", - "integrity": "sha512-DtBMo82pv1dFtUmHyr48beiuq792Sxohr+8Hm9zoxklYPfa6n0Z3Byjj2IV7bmr2IyqClnqEQhfgHJJ5QF0R5A==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", "funding": [ { "type": "github", @@ -14246,9 +14246,9 @@ } }, "domelementtype": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.2.0.tgz", - "integrity": "sha512-DtBMo82pv1dFtUmHyr48beiuq792Sxohr+8Hm9zoxklYPfa6n0Z3Byjj2IV7bmr2IyqClnqEQhfgHJJ5QF0R5A==" + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==" }, "domexception": { "version": "2.0.1", diff --git a/docs/src/_data/configuration.json b/docs/src/_data/configuration.json new file mode 100644 index 00000000..81d06957 --- /dev/null +++ b/docs/src/_data/configuration.json @@ -0,0 +1,326 @@ +[ + { + "name": "ignore", + "description": { + "en": "Ignore linter codes.", + "ru": "Игнорируйте коды линтера.", + "fr": "Ignore les codes de linter." + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "ignore=\"H014,H015\"" + }, + { + "name": ".djlintrc", + "value": "\"ignore\": \"H014,H015\"" + } + ] + }, + { + "name": "extension", + "description": { + "en": "Use to only find files with a specific extension.", + "ru": "Используется для поиска файлов только с определенным расширением.", + "fr": "Permet de trouver uniquement les fichiers ayant une extension spécifique." + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "extension=\"html.dj\"" + }, + { + "name": ".djlintrc", + "value": "\"extension\": \"html.dj\"" + } + ] + }, + { + "name": "custom_blocks", + "description": { + "en": "Use to indent custom code blocks. For example `{% toc %}...{% endtoc %}`", + "ru": "Используется для отступов в пользовательских блоках кода. Например, `{% toc %}...{% endtoc %}`", + "fr": "Sert à indenter les blocs de code personnalisés. Par exemple `{% toc %}...{% endtoc %}`" + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "custom_blocks=\"toc,example\"" + }, + { + "name": ".djlintrc", + "value": "\"custom_blocks\": \"toc,example\"" + } + ] + }, + { + "name": "custom_html", + "description": { + "en": "Use to indent custom HTML tags. For example `` or `` or ``", + "ru": "Используется для отступа пользовательских HTML-тегов. Например, `` или `` или ``.", + "fr": "Permet d'indenter les balises HTML personnalisées. Par exemple, `` ou `` ou ``." + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "custom_html=\"mjml,simple-greeting,mj-\\w+\"" + }, + { + "name": ".djlintrc", + "value": "\"custom_html\": \"mjml,simple-greeting,mj-\\w+\"" + } + ] + }, + { + "name": "indent", + "description": { + "en": "Use to change the code indentation. Default is 4 (four spaces).", + "ru": "Используется для изменения отступа кода. По умолчанию - 4 (четыре пробела).", + "fr": "Permet de modifier l'indentation du code. La valeur par défaut est 4 (quatre espaces)." + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "indent=3" + }, + { + "name": ".djlintrc", + "value": "\"indent\": \"3\"" + } + ] + }, + { + "name": "exclude", + "description": { + "en": "Override the default exclude paths.", + "ru": "Переопределите пути исключения по умолчанию.", + "fr": "Remplacer les chemins d'exclusion par défaut." + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "exclude=\".venv,venv,.tox,.eggs,...\"" + }, + { + "name": ".djlintrc", + "value": "\"exclude\": \".venv,venv,.tox,.eggs,...\"" + } + ] + }, + { + "name": "extend_exclude", + "description": { + "en": "Add additional paths to the default exclude.", + "ru": "Добавьте дополнительные пути к исключаемым по умолчанию.", + "fr": "Ajouter des chemins supplémentaires à l'exclusion par défaut." + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "extend_exclude=\".custom\"" + }, + { + "name": ".djlintrc", + "value": "\"extend_exclude\": \".custom\"" + } + ] + }, + { + "name": "blank_line_after_tag", + "description": { + "en": "Add an additional blank line after `{% ... %}` tag groups.", + "ru": "Добавьте дополнительную пустую строку после групп тегов `{% ... %}`.", + "fr": "Ajout d'une ligne vide supplémentaire après les groupes de balises `{% ... %}`." + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "blank_line_after_tag=\"load,extends,include\"" + }, + { + "name": ".djlintrc", + "value": "\"blank_line_after_tag\": \"load,extends,include\"" + } + ] + }, + { + "name": "profile", + "description": { + "en": "Set a profile for the template language. The profile will enable linter rules that apply to your template language, and may also change reformatting. For example, in `handlebars` there are no spaces inside `{{#if}}` tags.\n\nOptions:\n\n:::content\n\n- html (default)\n- django\n- jinja\n- nunjucks (for nunjucks and twig)\n- handlebars (for handlebars and mustache)\n- golang\n- angular\n :::", + "ru": "Установите профиль для языка шаблона. Профиль будет включать правила линтера, применимые к языку шаблонов, а также может изменять переформатирование. Например, в `handlebars` нет пробелов внутри тегов `{{#if}}`.\n\nOptions:\n\n:::content\n\n- html (default)\n- django\n- jinja\n- nunjucks (for nunjucks and twig)\n- handlebars (for handlebars and mustache)\n- golang\n- angular\n :::", + "fr": "Définissez un profil pour la langue du modèle. Le profil activera les règles de linter qui s'appliquent à votre langage de modèle, et peut également changer le reformatage. Par exemple, dans `handlebars`, il n'y a pas d'espaces dans les balises `{{#if}}`.\n\nOptions:\n\n:::content\n\n- html (default)\n- django\n- jinja\n- nunjucks (for nunjucks and twig)\n- handlebars (for handlebars and mustache)\n- golang\n- angular\n :::" + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "profile=\"django\"" + }, + { + "name": ".djlintrc", + "value": "\"profile\": \"django\"" + } + ] + }, + { + "name": "require_pragma", + "description": { + "en": "Only format or lint files that starts with a comment with only the text 'djlint:on'. The comment can be a HTML comment or a comment in the template language defined by the profile setting. If no profile is specified, a comment in any of the template languages is accepted.\n\n```html\n\n{# djlint:on #}\n{% comment %} djlint:on {% endcomment %}\n{{ /* djlint:on */ }}\n{{!-- djlint:on --}}\n```\n", + "ru": "Форматировать или линтовать только те файлы, которые начинаются с комментария, содержащего только текст 'djlint:on'. Комментарий может быть HTML-комментарием или комментарием на языке шаблонов, определенном настройкой профиля. Если профиль не указан, принимается комментарий на любом из языков шаблонов.\n\n```html\n\n{# djlint:on #}\n{% comment %} djlint:on {% endcomment %}\n{{ /* djlint:on */ }}\n{{!-- djlint:on --}}\n```\n", + "fr": "Ne formatez ou ne limez que les fichiers qui commencent par un commentaire contenant uniquement le texte 'djlint:on'. Le commentaire peut être un commentaire HTML ou un commentaire dans le langage de modèle défini par le paramètre de profil. Si aucun profil n'est spécifié, un commentaire dans l'un des langages de modèle est accepté.\n\n```html\n\n{# djlint:on #}\n{% comment %} djlint:on {% endcomment %}\n{{ /* djlint:on */ }}\n{{!-- djlint:on --}}\n```\n" + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "require_pragma=true" + }, + { + "name": ".djlintrc", + "value": "\"require_pragma\": \"true\"" + } + ] + }, + { + "name": "max_line_length", + "description": { + "en": "Formatter will attempt to put some html and template tags on a single line instead of wrapping them if the line length will not exceed this value.", + "ru": "Форматировщик попытается разместить некоторые html и шаблонные теги на одной строке вместо того, чтобы обернуть их, если длина строки не превышает этого значения.", + "fr": "Le formateur essaiera de mettre certaines balises html et template sur une seule ligne au lieu de les envelopper si la longueur de la ligne ne dépasse pas cette valeur." + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "max_line_length=120" + }, + { + "name": ".djlintrc", + "value": "\"max_line_length\": \"120\"" + } + ] + }, + { + "name": "max_attribute_length", + "description": { + "en": "Formatter will attempt to wrap tag attributes if the attribute length exceeds this value.", + "ru": "Форматировщик попытается обернуть атрибуты тега, если длина атрибута превышает это значение.", + "fr": "Le formateur tentera d'envelopper les attributs de la balise si la longueur de l'attribut dépasse cette valeur." + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "max_attribute_length=10" + }, + { + "name": ".djlintrc", + "value": "\"max_attribute_length\": \"10\"" + } + ] + }, + { + "name": "use_gitignore", + "description": { + "en": "Add .gitignore excludes to the default exclude.", + "ru": "Добавьте исключения .gitignore к исключениям по умолчанию.", + "fr": "Ajouter les exclusions .gitignore à l'exclusion par défaut." + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "use_gitignore=True" + }, + { + "name": ".djlintrc", + "value": "\"use_gitignore\": \"True\"" + } + ] + }, + { + "name": "format_attribute_template_tags", + "description": { + "en": "Formatter will attempt to format template syntax inside of tag attributes. Disabled by default.", + "ru": "Форматировщик будет пытаться форматировать синтаксис шаблона внутри атрибутов тега. По умолчанию отключен.", + "fr": "Le formateur tentera de formater la syntaxe des modèles à l'intérieur des attributs des balises. Désactivé par défaut." + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "format_attribute_template_tags=true" + }, + { + "name": ".djlintrc", + "value": "\"format_attribute_template_tags\": \"true\"" + } + ] + }, + { + "name": "linter_output_format", + "description": { + "en": "Customize order of output message. Default=\"{code} {line} {message} {match}\". If `{filename}` is not include in message, then the output will be grouped by file and a header will automatically be added to each group.\n\nOptional variables:\n::: content\n\n- `{filename}`\n- `{line}`\n- `{code}`\n- `{message}`\n- `{match}`\n :::", + "ru": "Настройка порядка вывода сообщения. По умолчанию=\"{code} {line} {message} {match}\". Если `{filename}` не включено в сообщение, то вывод будет сгруппирован по файлам и к каждой группе будет автоматически добавлен заголовок.\n\nOptional variables:\n::: content\n\n- `{filename}`\n- `{line}`\n- `{code}`\n- `{message}`\n- `{match}`\n :::", + "fr": "Personnalise l'ordre du message de sortie. Défaut=\"{code} {ligne} {message} {match}\". Si `{filename}` n'est pas inclus dans le message, alors la sortie sera groupée par fichier et un en-tête sera automatiquement ajouté à chaque groupe.\n\nOptional variables:\n::: content\n\n- `{filename}`\n- `{line}`\n- `{code}`\n- `{message}`\n- `{match}`\n :::" + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "linter_output_format=\"{filename}:{line}: {code} {message} {match}\"" + }, + { + "name": ".djlintrc", + "value": "\"linter_output_format\": \"{filename}:{line}: {code} {message} {match}\"" + } + ] + }, + { + "name": "preserve_leading_space", + "description": { + "en": "Preserve leading space on text, where possible. Ideal for non-html template files where text indent is intentional.", + "ru": "Сохраняет пробелы в тексте, где это возможно. Идеально подходит для не-html файлов шаблонов, где отступ текста является намеренным.", + "fr": "Préserve l'espace de tête du texte, dans la mesure du possible. Idéal pour les fichiers de modèles non-html où l'indentation du texte est intentionnelle." + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "preserve_leading_space=true" + }, + { + "name": ".djlintrc", + "value": "\"preserve_leading_space\": true" + } + ] + }, + { + "name": "preserve_blank_lines", + "description": { + "en": "Preserve blank where possible. Ideal for non-html template files where blank lines are intentional.", + "ru": "Сохраняйте пробелы там, где это возможно. Идеально подходит для не-html файлов шаблонов, где пустые строки являются намеренными.", + "fr": "Préserve les blancs lorsque cela est possible. Idéal pour les fichiers de modèles non-html où les lignes vides sont intentionnelles." + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "preserve_blank_lines=true" + }, + { + "name": ".djlintrc", + "value": "\"preserve_blank_lines\": true" + } + ] + }, + { + "name": "per_file_ignores", + "description": { + "en": "Ignore linter rules on a per-file basis.", + "ru": "Игнорировать правила линтера на основе каждого файла.", + "fr": "Ignorer les règles de linter sur une base par fichier." + }, + "usage": [ + { + "name": "pyproject.toml", + "value": "[tool.djlint.per-file-ignores]\n\"file.html\"= \"H026,H025\"\n\"file_two.html\"=\"H001\"" + }, + { + "name": ".djlintrc", + "value": "\"per-file-ignores\": {\n \"file.html\": \"H026,H025\",\n \"file_two.html\":\"H001\"\n }" + } + ] + } +] diff --git a/docs/src/_includes/foot.njk b/docs/src/_includes/foot.njk index 9971fc75..6822aaa4 100644 --- a/docs/src/_includes/foot.njk +++ b/docs/src/_includes/foot.njk @@ -11,7 +11,7 @@
-
diff --git a/docs/src/_utils/scripts.11ty.js b/docs/src/_utils/scripts.11ty.js index 907289ca..77b626f8 100644 --- a/docs/src/_utils/scripts.11ty.js +++ b/docs/src/_utils/scripts.11ty.js @@ -14,7 +14,11 @@ module.exports = class { async render() { await esbuild.build({ entryPoints: ['src/static/js/hamburger.js'], - inject: ['./src/static/js/animate.js', './src/static/js/modal.js'], + inject: [ + './src/static/js/animate.js', + './src/static/js/modal.js', + './src/static/js/tabs.js', + ], bundle: true, minify: true, outfile: `_site/static/js/${generateContentHash( diff --git a/docs/src/docs/configuration.md b/docs/src/docs/configuration.md index 25ed2a46..edf94596 100644 --- a/docs/src/docs/configuration.md +++ b/docs/src/docs/configuration.md @@ -2,6 +2,7 @@ description: djLint configuration for HTML Template Linting and Formatting. Take advantage of the many formatter options. title: Configuration keywords: template linter, template formatter, djLint, HTML, templates, formatter, linter, configuration +date: Last Modified --- # Configuration @@ -23,401 +24,35 @@ The format for `.djlintrc` is `json`. } ``` -## ignore +{% for option in configuration %} -Ignore linter codes. +### {{ option.name }} -Usage: +

{{ option.description[locale or "en"] | markdown | safe }}

-**pyproject.toml** +
+
    -```ini -ignore="H014,H015" -``` - -**.djlintrc** - -```json -{ - "ignore": "H014,H015" -} -``` +{% for flag in option.usage %} -## extension +
  • {{ flag.name }}
  • -Use to only find files with a specific extension. +{% endfor %} -Usage: +
+
-**pyproject.toml** +
+{% for flag in option.usage %} +
-```ini -extension="html.dj" -``` - -**.djlintrc** - -```json -{ - "extension": "html.dj" -} +```{% if flag.name == "pyproject.toml" %}toml{% else %}json{% endif %} +{{ flag.value | safe }} ``` -## custom_blocks - -Use to indent custom code blocks. For example {% raw %}`{% toc %}...{% endtoc %}`{% endraw %} - -Usage: - -**pyproject.toml** - -```ini -custom_blocks="toc,example" -``` - -**.djlintrc** - -```json -{ - "custom_blocks": "toc,example" -} -``` - -## custom_html - -Use to indent custom HTML tags. For example `` or `` or `` +
+{% endfor %} -Usage: +
-**pyproject.toml** - -```ini -custom_html="mjml,simple-greeting,mj-\\w+" -``` - -**.djlintrc** - -```json -{ - "custom_html": "mjml,simple-greeting,mj-\\w+" -} -``` - -## indent - -Use to change the code indentation. Default is 4 (four spaces). - -Usage: - -**pyproject.toml** - -```ini -indent=3 -``` - -**.djlintrc** - -```json -{ - "indent": "3" -} -``` - -## exclude - -Override the default exclude paths. - -Usage: - -**pyproject.toml** - -```ini -exclude=".venv,venv,.tox,.eggs,..." -``` - -**.djlintrc** - -```json -{ - "exclude": ".venv,venv,.tox,.eggs,..." -} -``` - -## extend_exclude - -Add additional paths to the default exclude. - -Usage: - -**pyproject.toml** - -```ini -extend_exclude=".custom" -``` - -**.djlintrc** - -```json -{ - "extend_exclude": ".custom" -} -``` - -## blank_line_after_tag - -Add an additional blank line after {% raw %}`{% ... %}`{% endraw %} tag groups. - -Usage: - -**pyproject.toml** - -```ini -blank_line_after_tag="load,extends,include" -``` - -**.djlintrc** - -```json -{ - "blank_line_after_tag": "load,extends,include" -} -``` - -## profile - -Set a profile for the template language. The profile will enable linter rules that apply to your template language, and may also change reformatting. For example, in `handlebars` there are no spaces inside {% raw %}`{{#if}}`{% endraw %} tags. - -Options: - -:::content - -- html (default) -- django -- jinja -- nunjucks (for nunjucks and twig) -- handlebars (for handlebars and mustache) -- golang -- angular - ::: - -Usage: - -**pyproject.toml** - -```ini -profile="django" -``` - -**.djlintrc** - -```json -{ - "profile": "django" -} -``` - -## require_pragma - -Only format or lint files that starts with a comment with only the text 'djlint:on'. The comment can be a HTML comment or a comment in the template language defined by the profile setting. If no profile is specified, a comment in any of the template languages is accepted. - -Usage: - -**pyproject.toml** - -```ini -require_pragma=true -``` - -**.djlintrc** - -```json -{ - "require_pragma": "true" -} -``` - -{% raw %} - -```html - -or {# djlint:on #} or {% comment %} djlint:on {% endcomment %} or {{ /* -djlint:on */ }} or {{!-- djlint:on --}} -``` - -{% endraw %} - -## max_line_length - -Formatter will attempt to put some html and template tags on a single line instead of wrapping them if the line length will not exceed this value. - -Usage: - -**pyproject.toml** - -```ini -max_line_length=120 -``` - -**.djlintrc** - -```json -{ - "max_line_length": "120" -} -``` - -## max_attribute_length - -Formatter will attempt to wrap tag attributes if the attribute length exceeds this value. - -Usage: - -**pyproject.toml** - -```ini -max_attribute_length=10 -``` - -**.djlintrc** - -```json -{ - "max_attribute_length": "10" -} -``` - -## use_gitignore - -Add .gitignore excludes to the default exclude. - -Usage: - -**pyproject.toml** - -```ini -use_gitignore=True -``` - -**.djlintrc** - -```json -{ - "use_gitignore": "True" -} -``` - -## format_attribute_template_tags - -Formatter will attempt to format template syntax inside of tag attributes. Disabled by default. - -Usage: - -**pyproject.toml** - -```ini -format_attribute_template_tags=true -``` - -**.djlintrc** - -```json -{ - "format_attribute_template_tags": "true" -} -``` - -For example, with this option enabled, the following html will be acceptable: - -```html -{% raw %} - -{% endraw %} -``` - -## linter_output_format - -Customize order of output message. Default="{code} {line} {message} {match}". If `{filename}` is not include in message, then the output will be grouped by file and a header will automatically be added to each group. - -Optional variables: -::: content - -- `{filename}` -- `{line}` -- `{code}` -- `{message}` -- `{match}` - ::: - -Usage: - -**pyproject.toml** - -```ini -linter_output_format="{filename}:{line}: {code} {message} {match}" -``` - -**.djlintrc** - -```json -{ - "linter_output_format": "{filename}:{line}: {code} {message} {match}" -} -``` - -## preserve_leading_space - -Preserve leading space on text, where possible. Ideal for non-html template files where text indent is intentional. - -Usage: - -**flag** - -```bash ---preserve-leading-space -``` - -**pyproject.toml** - -```ini -preserve_leading_space=true -``` - -**.djlintrc** - -```json -{ - "preserve_leading_space": true -} -``` - -## preserve_blank_lines - -Preserve blank where possible. Ideal for non-html template files where blank lines are intentional. - -Usage: - -**flag** - -```bash ---preserve-blank-lines -``` - -**pyproject.toml** - -```ini -preserve_blank_lines=true -``` - -**.djlintrc** - -```json -{ - "preserve_blank_lines": true -} -``` +{% endfor %} diff --git a/docs/src/docs/getting-started.md b/docs/src/docs/getting-started.md index d6dfcbb5..c1e1b31e 100644 --- a/docs/src/docs/getting-started.md +++ b/docs/src/docs/getting-started.md @@ -45,6 +45,8 @@ Options: --lint Lint for common issues. [default option] --use-gitignore Use .gitignore file to extend excludes. --warn Return errors as warnings. + --preserve-leading-space Attempt to preserve leading space on text. + --preserve-blank-lines Attempt to preserve blank lines. -h, --help Show this message and exit. ``` diff --git a/docs/src/fr/docs/configuration.md b/docs/src/fr/docs/configuration.md index a444449f..f473de83 100644 --- a/docs/src/fr/docs/configuration.md +++ b/docs/src/fr/docs/configuration.md @@ -23,401 +23,35 @@ Le format du fichier `djlintrc` est `json`. } ``` -## ignore +{% for option in configuration %} -Ignore les codes de linter. +### {{ option.name }} -Utilisation : +

{{ option.description[locale or "en"] | markdown | safe }}

-**pyproject.toml** +
+
    -```ini -ignore="H014,H015" -``` - -**.djlintrc** - -```json -{ - "ignore": "H014,H015" -} -``` +{% for flag in option.usage %} -## extension +
  • {{ flag.name }}
  • -Permet de trouver uniquement les fichiers ayant une extension spécifique. +{% endfor %} -Utilisation: +
+
-**pyproject.toml** +
+{% for flag in option.usage %} +
-```ini -extension="html.dj" -``` - -**.djlintrc** - -```json -{ - "extension": "html.dj" -} +```{% if flag.name == "pyproject.toml" %}toml{% else %}json{% endif %} +{{ flag.value | safe }} ``` -## custom_blocks - -Sert à indenter les blocs de code personnalisés. Par exemple {% raw %}`{% toc %}...{% endtoc %}`{% endraw %} - -Utilisation: - -**pyproject.toml** - -```ini -custom_blocks="toc,example" -``` - -**.djlintrc** - -```json -{ - "custom_blocks": "toc,example" -} -``` - -## custom_html - -Permet d'indenter les balises HTML personnalisées. Par exemple, `` ou `` ou ``. +
+{% endfor %} -Utilisation: +
-**pyproject.toml** - -```ini -custom_html="mjml,simple-greeting,mj-\\w+" -``` - -**.djlintrc** - -```json -{ - "custom_html": "mjml,simple-greeting,mj-\\w+" -} -``` - -## indent - -Permet de modifier l'indentation du code. La valeur par défaut est 4 (quatre espaces). - -Utilisation: - -**pyproject.toml** - -```ini -indent=3 -``` - -**.djlintrc** - -```json -{ - "indent": "3" -} -``` - -## exclude - -Remplacer les chemins d'exclusion par défaut. - -Utilisation: - -**pyproject.toml** - -```ini -exclude=".venv,venv,.tox,.eggs,..." -``` - -**.djlintrc** - -```json -{ - "exclude": ".venv,venv,.tox,.eggs,..." -} -``` - -## extend_exclude - -Ajouter des chemins supplémentaires à l'exclusion par défaut. - -Utilisation: - -**pyproject.toml** - -```ini -extend_exclude=".custom" -``` - -**.djlintrc** - -```json -{ - "extend_exclude": ".custom" -} -``` - -## blank_line_after_tag - -Ajout d'une ligne vide supplémentaire après les groupes de balises {% raw %}`{% ... %}`{% endraw %}. - -Utilisation: - -**pyproject.toml** - -```ini -blank_line_after_tag="load,extends,include" -``` - -**.djlintrc** - -```json -{ - "blank_line_after_tag": "load,extends,include" -} -``` - -## profile - -Définissez un profil pour la langue du modèle. Le profil activera les règles de linter qui s'appliquent à votre langage de modèle, et peut également changer le reformatage. Par exemple, dans `handlebars`, il n'y a pas d'espaces dans les balises {% raw %}`{{#if}}`{% endraw %}. - -Options: - -:::content - -- html (par défaut) -- django -- jinja -- nunjucks (pour nunjucks et twig) -- handlebars (pour handlebars et mustache) -- golang -- angulaire - ::: - -Utilisation: - -**pyproject.toml** - -```ini -profile="django" -``` - -**.djlintrc** - -```json -{ - "profile": "django" -} -``` - -## require_pragma - -Ne formatez ou ne limez que les fichiers qui commencent par un commentaire contenant uniquement le texte 'djlint:on'. Le commentaire peut être un commentaire HTML ou un commentaire dans le langage de modèle défini par le paramètre de profil. Si aucun profil n'est spécifié, un commentaire dans l'un des langages de modèle est accepté. - -Utilisation: - -**pyproject.toml** - -```ini -require_pragma=true -``` - -**.djlintrc** - -```json -{ - "require_pragma": "true" -} -``` - -{% raw %} - -```html - -ou {# djlint:on #} ou {% comment %} djlint:on {% endcomment %} ou {{ /* -djlint:on */ }} ou {{!-- djlint:on --}} -``` - -{% endraw %} - -## max_line_length - -Le formateur essaiera de mettre certaines balises html et template sur une seule ligne au lieu de les envelopper si la longueur de la ligne ne dépasse pas cette valeur. - -Utilisation: - -**pyproject.toml** - -```ini -max_line_length=120 -``` - -**.djlintrc** - -```json -{ - "max_line_length": "120" -} -``` - -## max_attribute_length - -Le formateur tentera d'envelopper les attributs de la balise si la longueur de l'attribut dépasse cette valeur. - -Utilisation: - -**pyproject.toml** - -```ini -max_attribute_length=10 -``` - -**.djlintrc** - -```json -{ - "max_attribute_length": "10" -} -``` - -## use_gitignore - -Ajouter les exclusions .gitignore à l'exclusion par défaut. - -Utilisation: - -**pyproject.toml** - -```ini -use_gitignore=True -``` - -**.djlintrc** - -```json -{ - "use_gitignore": "True" -} -``` - -## format_attribute_template_tags - -Le formateur tentera de formater la syntaxe des modèles à l'intérieur des attributs des balises. Désactivé par défaut. - -Utilisation: - -**pyproject.toml** - -```ini -format_attribute_template_tags=true -``` - -**.djlintrc** - -```json -{ - "format_attribute_template_tags": "true" -} -``` - -Par exemple, avec cette option activée, le html suivant sera acceptable : - -```html -{% raw %} - -{% endraw %} -``` - -## linter_output_format - -Personnalise l'ordre du message de sortie. Défaut="{code} {ligne} {message} {match}". Si `{filename}` n'est pas inclus dans le message, alors la sortie sera groupée par fichier et un en-tête sera automatiquement ajouté à chaque groupe. - -Variables facultatives : -::: content - -- `{filename}` -- `{line}` -- `{code}` -- `{message}` -- `{match}` - ::: - -Utilisation: - -**pyproject.toml** - -```ini -linter_output_format="{filename}:{line}: {code} {message} {match}" -``` - -**.djlintrc** - -```json -{ - "linter_output_format": "{filename}:{line}: {code} {message} {match}" -} -``` - -## preserve_leading_space - -Préserve l'espace de tête du texte, dans la mesure du possible. Idéal pour les fichiers de modèles non-html où l'indentation du texte est intentionnelle. - -Utilisation: - -**flag** - -```bash ---preserve-leading-space -``` - -**pyproject.toml** - -```ini -preserve_leading_space=true -``` - -**.djlintrc** - -```json -{ - "preserve_leading_space": true -} -``` - -## preserve_blank_lines - -Préserve les blancs lorsque cela est possible. Idéal pour les fichiers de modèles non-html où les lignes vides sont intentionnelles. - -Utilisation: - -**flag** - -```bash ---preserve-blank-lines -``` - -**pyproject.toml** - -```ini -preserve_blank_lines=true -``` - -**.djlintrc** - -```json -{ - "preserve_blank_lines": true -} -``` +{% endfor %} diff --git a/docs/src/fr/docs/getting-started.md b/docs/src/fr/docs/getting-started.md index ee23f55d..425de055 100644 --- a/docs/src/fr/docs/getting-started.md +++ b/docs/src/fr/docs/getting-started.md @@ -45,6 +45,8 @@ Options: --lint Lint for common issues. [default option] --use-gitignore Use .gitignore file to extend excludes. --warn Return errors as warnings. + --preserve-leading-space Attempt to preserve leading space on text. + --preserve-blank-lines Attempt to preserve blank lines. -h, --help Show this message and exit. ``` diff --git a/docs/src/ru/docs/configuration.md b/docs/src/ru/docs/configuration.md index abc22069..43b06773 100644 --- a/docs/src/ru/docs/configuration.md +++ b/docs/src/ru/docs/configuration.md @@ -21,400 +21,35 @@ keywords: облицовка шаблонов, форматер шаблонов } ``` -## ignore +{% for option in configuration %} -Игнорируйте коды линтера. +### {{ option.name }} -Использование: +

{{ option.description[locale or "en"] | markdown | safe }}

-**pyproject.toml** +
+
    -```ini -ignore="H014,H015" -``` - -**.djlintrc** - -```json -{ - "ignore": "H014,H015" -} -``` - -## extension - -Используется для поиска файлов только с определенным расширением. - -Использование: - -**pyproject.toml** - -```ini -extension="html.dj" -``` - -**.djlintrc** - -```json -{ - "extension": "html.dj" -} -``` - -## custom_blocks - -Используется для отступов в пользовательских блоках кода. Например, {% raw %}`{% toc %}...{% endtoc %}`{% endraw %} - -Использование: - -**pyproject.toml** - -```ini -custom_blocks="toc,example" -``` - -**.djlintrc** - -```json -{ - "custom_blocks": "toc,example" -} -``` - -## custom_html - -Используется для отступа пользовательских HTML-тегов. Например, `` или `` или ``. - -Использование: - -**pyproject.toml** - -```ini -custom_html="mjml,simple-greeting,mj-\\w+" -``` - -**.djlintrc** - -```json -{ - "custom_html": "mjml,simple-greeting,mj-\\w+" -} -``` - -## indent - -Используется для изменения отступа кода. По умолчанию - 4 (четыре пробела). - -Использование: - -**pyproject.toml** - -```ini -indent=3 -``` - -**.djlintrc** - -```json -{ - "indent": "3" -} -``` - -## exclude - -Переопределите пути исключения по умолчанию. - -Использование: - -**pyproject.toml** - -```ini -exclude=".venv,venv,.tox,.eggs,..." -``` - -**.djlintrc** - -```json -{ - "exclude": ".venv,venv,.tox,.eggs,..." -} -``` - -## extend_exclude - -Добавьте дополнительные пути к исключаемым по умолчанию. - -Использование: - -**pyproject.toml** - -```ini -extend_exclude=".custom" -``` - -**.djlintrc** - -```json -{ - "extend_exclude": ".custom" -} -``` - -## blank_line_after_tag - -Добавьте дополнительную пустую строку после групп тегов {% raw %}`{% ... %}`{% endraw %}. - -Использование: - -**pyproject.toml** - -```ini -blank_line_after_tag="load,extends,include" -``` - -**.djlintrc** - -```json -{ - "blank_line_after_tag": "load,extends,include" -} -``` - -## profile - -Установите профиль для языка шаблона. Профиль будет включать правила линтера, применимые к языку шаблонов, а также может изменять переформатирование. Например, в `handlebars` нет пробелов внутри тегов {% raw %}`{{#if}}`{% endraw %}. -Параметры: - -:::content - -- html (по умолчанию) -- django -- jinja -- nunjucks (для nunjucks и twig) -- handlebars (для handlebars и mustache) -- golang -- angular - ::: - -Использование: - -**pyproject.toml** - -```ini -profile="django" -``` - -**.djlintrc** - -```json -{ - "profile": "django" -} -``` - -## require_pragma - -Форматировать или линтовать только те файлы, которые начинаются с комментария, содержащего только текст 'djlint:on'. Комментарий может быть HTML-комментарием или комментарием на языке шаблонов, определенном настройкой профиля. Если профиль не указан, принимается комментарий на любом из языков шаблонов. - -Использование: - -**pyproject.toml** - -```ini -require_pragma=true -``` - -**.djlintrc** - -```json -{ - "require_pragma": "true" -} -``` - -{% raw %} - -```html - -или {# djlint:on #} или {% comment %} djlint:on {% endcomment %} или {{ /* -djlint:on */ }} или {{!-- djlint:on --}} -``` - -{% endraw %} - -## max_line_length - -Форматировщик попытается разместить некоторые html и шаблонные теги на одной строке вместо того, чтобы обернуть их, если длина строки не превышает этого значения. - -Использование: - -**pyproject.toml** - -```ini -max_line_length=120 -``` - -**.djlintrc** - -```json -{ - "max_line_length": "120" -} -``` - -## max_attribute_length - -Форматировщик попытается обернуть атрибуты тега, если длина атрибута превышает это значение. - -Использование: - -**pyproject.toml** - -```ini -max_attribute_length=10 -``` - -**.djlintrc** - -```json -{ - "max_attribute_length": "10" -} -``` - -## use_gitignore - -Добавьте исключения .gitignore к исключениям по умолчанию. - -Использование: - -**pyproject.toml** - -```ini -use_gitignore=True -``` - -**.djlintrc** - -```json -{ - "use_gitignore": "True" -} -``` - -## format_attribute_template_tags - -Форматировщик будет пытаться форматировать синтаксис шаблона внутри атрибутов тега. По умолчанию отключен. - -Использование: - -**pyproject.toml** - -```ini -format_attribute_template_tags=true -``` - -**.djlintrc** - -```json -{ - "format_attribute_template_tags": "true" -} -``` - -Например, если эта опция включена, то допустимым будет следующий html: - -```html -{% raw %} - -{% endraw %} -``` - -## linter_output_format - -Настройка порядка вывода сообщения. По умолчанию="{code} {line} {message} {match}". Если `{filename}` не включено в сообщение, то вывод будет сгруппирован по файлам и к каждой группе будет автоматически добавлен заголовок. - -Необязательные переменные: -::: content - -- `{filename}` -- `{line}` -- `{code}` -- `{message}` -- `{match}` - ::: - -Использование: - -**pyproject.toml** - -```ini -linter_output_format="{filename}:{line}: {code} {message} {match}" -``` - -**.djlintrc** +{% for flag in option.usage %} -```json -{ - "linter_output_format": "{filename}:{line}: {code} {message} {match}" -} -``` - -## preserve_leading_space - -Сохраняет пробелы в тексте, где это возможно. Идеально подходит для не-html файлов шаблонов, где отступ текста является намеренным. - -Использование: - -**flag** - -```bash ---preserve-leading-space -``` - -**pyproject.toml** - -```ini -preserve_leading_space=true -``` +
  • {{ flag.name }}
  • -**.djlintrc** +{% endfor %} -```json -{ - "preserve_leading_space": true -} -``` - -## preserve_blank_lines - -Сохраняйте пробелы там, где это возможно. Идеально подходит для не-html файлов шаблонов, где пустые строки являются намеренными. - -Использование: +
+
-**flag** +
+{% for flag in option.usage %} +
-```bash ---preserve-blank-lines +```{% if flag.name == "pyproject.toml" %}toml{% else %}json{% endif %} +{{ flag.value | safe }} ``` -**pyproject.toml** +
+{% endfor %} -```ini -preserve_blank_lines=true -``` +
-**.djlintrc** - -```json -{ - "preserve_blank_lines": true -} -``` +{% endfor %} diff --git a/docs/src/ru/docs/getting-started.md b/docs/src/ru/docs/getting-started.md index b67cb0ae..76b1cbcb 100644 --- a/docs/src/ru/docs/getting-started.md +++ b/docs/src/ru/docs/getting-started.md @@ -45,6 +45,8 @@ Options: --lint Lint for common issues. [default option] --use-gitignore Use .gitignore file to extend excludes. --warn Return errors as warnings. + --preserve-leading-space Attempt to preserve leading space on text. + --preserve-blank-lines Attempt to preserve blank lines. -h, --help Show this message and exit. ``` diff --git a/docs/src/static/css/site.scss b/docs/src/static/css/site.scss index 4c90435b..d06b18d8 100644 --- a/docs/src/static/css/site.scss +++ b/docs/src/static/css/site.scss @@ -30,6 +30,10 @@ pre .tag { padding-right: unset; white-space: unset; } +pre .section { + padding: unset; +} + @import '../../../node_modules/prismjs/themes/prism'; @include fontFace( diff --git a/docs/src/static/js/tabs.js b/docs/src/static/js/tabs.js new file mode 100644 index 00000000..128f1a99 --- /dev/null +++ b/docs/src/static/js/tabs.js @@ -0,0 +1,34 @@ +document.addEventListener('click', function (e) { + if ( + e.target.closest('.tabs li a') && + e.target.closest('.tabs li a').hasAttribute('tab') + ) { + console.log('tab click'); + + // change active tab button + var tabLinks = e.target.closest('.tabs').querySelectorAll('li.is-active'); + + for (var i = 0; i < tabLinks.length; i++) { + tabLinks[i].classList.remove('is-active'); + } + + e.target.closest('li').classList.add('is-active'); + + // change active tab + + // find container with tab + var tabContainer = document + .querySelector('.tab-container .tab#' + e.target.getAttribute('tab')) + .closest('.tab-container'); + + var tabs = tabContainer.querySelectorAll('.tab.is-active'); + + for (var i = 0; i < tabs.length; i++) { + tabs[i].classList.remove('is-active'); + } + + tabContainer + .querySelector('.tab#' + e.target.getAttribute('tab')) + .classList.add('is-active'); + } +}); diff --git a/package-lock.json b/package-lock.json index 6bc32ec7..29ea0497 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "djlint", - "version": "1.3.0", + "version": "1.4.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "djlint", - "version": "1.3.0", + "version": "1.4.0", "hasInstallScript": true, "license": "GPL-3.0-or-later", "dependencies": { diff --git a/src/djlint/lint.py b/src/djlint/lint.py index 5a438470..26244791 100644 --- a/src/djlint/lint.py +++ b/src/djlint/lint.py @@ -54,10 +54,20 @@ def lint_file(config: Config, this_file: Path) -> Dict: for m in re.finditer(r"(?:.*\n)|(?:[^\n]+$)", html) ] + ignored_rules: List[str] = [] + + # remove ignored rules for file + for pattern, rules in config.per_file_ignores.items(): + if re.search(pattern, this_file.as_posix(), re.VERBOSE): + ignored_rules += [x.strip() for x in rules.split(",")] + for rule in config.linter_rules: rule = rule["rule"] for pattern in rule["patterns"]: + # skip ignored rules + if rule["name"] in ignored_rules: + continue # rule H025 is a special case where the output must be an even number. if rule["name"] == "H025": diff --git a/src/djlint/settings.py b/src/djlint/settings.py index 9205b1a0..719971cf 100644 --- a/src/djlint/settings.py +++ b/src/djlint/settings.py @@ -327,6 +327,8 @@ def __init__( x.strip() for x in extend_exclude.split(",") ) + self.per_file_ignores = djlint_settings.get("per-file-ignores", {}) + # add blank line after load tags self.blank_line_after_tag: Optional[str] = djlint_settings.get( "blank_line_after_tag", None diff --git a/tests/test_config/test_per_file_ignores/__init__.py b/tests/test_config/test_per_file_ignores/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/test_config/test_per_file_ignores/html.html b/tests/test_config/test_per_file_ignores/html.html new file mode 100644 index 00000000..312de058 --- /dev/null +++ b/tests/test_config/test_per_file_ignores/html.html @@ -0,0 +1,2 @@ +
+
diff --git a/tests/test_config/test_per_file_ignores/pyproject.toml b/tests/test_config/test_per_file_ignores/pyproject.toml new file mode 100644 index 00000000..9e0d4eb8 --- /dev/null +++ b/tests/test_config/test_per_file_ignores/pyproject.toml @@ -0,0 +1,2 @@ +[tool.djlint.per-file-ignores] +"html.html"= "H025" diff --git a/tests/test_config/test_per_file_ignores/test_config.py b/tests/test_config/test_per_file_ignores/test_config.py new file mode 100644 index 00000000..b7a29c70 --- /dev/null +++ b/tests/test_config/test_per_file_ignores/test_config.py @@ -0,0 +1,25 @@ +"""Djlint tests specific to pyproject.toml configuration. + +run:: + + pytest tests/test_config/test_per_file_ignores/test_config.py --cov=src/djlint --cov-branch \ + --cov-report xml:coverage.xml --cov-report term-missing + +for a single test, run:: + + pytest tests/test_config.py::test_custom_html --cov=src/djlint \ + --cov-branch --cov-report xml:coverage.xml --cov-report term-missing + +""" +# pylint: disable=C0116 + + +from click.testing import CliRunner + +from src.djlint import main as djlint + + +def test_ignores(runner: CliRunner) -> None: + result = runner.invoke(djlint, ["tests/test_config/test_per_file_ignores"]) + assert "H025" not in result.output + assert "H020" in result.output