Skip to content

About

Linters of Odoo addons that complement pylint-odoo

Resources

Code of conduct

Contributing

Security policy

Stars

26 stars

Watchers

18 watching

Forks

Latest commit

 

History

233 Commits

Folders and files

Build Status codecov version wheel supported-versions commits-since code-style-black

odoo-pre-commit-hooks

OCA's custom pre-commit hooks for Odoo modules

Installation

You don't need to install it directly only configure your ".pre-commit-config.yaml" file

You even can install it directly:

  • Installing from pypi:

    • pip install -U oca-odoo-pre-commit-hooks
  • Installing from github:

    • pip install --force-reinstall -U git+https://github.com/OCA/odoo-pre-commit-hooks.git@main

Usage pre-commit-config.yaml

Add to your ".pre-commit-config.yaml" configuration file the following input

    - repo: https://github.com/OCA/odoo-pre-commit-hooks
        rev: v0.2.29
        hooks:
        - id: oca-checks-odoo-module
        - id: oca-checks-po
          args: ["--fix"]

Usage directly the entry points

If you install directly the package use the entry point:

oca-checks-odoo-module --help
oca-checks-po --help

Skip one xml-check for only one file

If you need to skip one check in one particular XML file you can use the follow comment

<?xml version="1.0" encoding="utf-8"?>
<!-- oca-hooks:disable=xml-check-to-skip -->
<odoo>
...
</odoo>
<?xml version="1.0" encoding="utf-8"?>
<!-- oca-hooks:disable=xml-check-to-skip,
                       xml-check-to-skip2 -->
<odoo>
...
</odoo>

The position of the comment it is not relative to the line that throw the check

It disable the entire file

Configuration

Behavior can be configured through several methods and as of now only consists of enabling/disabling checks.

Enabling or Disabling Checks

Each available hook consists of multiple checks which can be enabled/disabled using any of the following methods (ordered by priority):

  1. As an argument e.g., oca-checks-odoo --enable=check-to-enable --disable=check-to-disable1,check-to-disable2
  2. Using environment variables OCA_HOOKS_ENABLE or OCA_HOOKS_DISABLE e.g., export OCA_HOOKS_ENABLE=check1,check2
  3. A configuration file. The path to it can be specified with the argument --config. Alternatively a file named .oca_hooks.cfg will be looked for (by default) in the following locations (in order):
    1. Current working directory
    2. Repo's root
    3. User's home

Using a Configuration File

To enable or disable checks using a configuration file, add a disable or enable key under the MESSAGES_CONTROL section. For example:

[MESSAGES_CONTROL]
enable=check-enable1,check-enable2
disable=check-to-disable

To customize the xml-tag-position check, you can also define xml_attributes_order in the same section. Each group declares equivalent attributes, and groups are enforced from left to right.

[MESSAGES_CONTROL]
xml_attributes_order=[t-if, t-else, t-elif], [id, t-att-id, t-attf-id], [class, t-att-class, t-attf-class]

Custom example:

[MESSAGES_CONTROL]
xml_attributes_order=[class], [id], [t-if]

The same value can also be passed from CLI with --xml-attributes-order.

As stated before, each source has a certain priority. This means that if the environment variable OCA_HOOKS_ENABLE=check1 exists, the configuration file above would not have any effect when it comes to enabling checks, and the only enabled check will be check1.

However, if OCA_HOOKS_DISABLE is not set, the configuration file will still have an effect and check-to-disable will be disabled.

Checks

  • Check weblate-component-too-long Check if the component is too long Weblate have 100 characters limit for repository name + Odoo Version + module name e.g. The following module: https://github.com/OCA/account-financial-reporting/tree/18.0/account_tax_balance Generates the following component: account-financial-reporting-18.0-account_tax_balance

  • Check file-not-used Check if there is a file created but not referenced from manifest.py

  • Check manifest-syntax-error Check if the manifest file has syntax error

  • Check prefer-readme-rst Check if the module has README.md file to prefer README.rst file

  • Check use-header-comments Check if the py file has comments '# comment' only in the header of python files Except valid comments e.g. pylint, flake8, shebang or comments in the middle (not header)

  • Check csv-duplicate-record-id duplicate CSV "id" AKA xmlid but for CSV files

  • Check csv-syntax-error Check syntax error for CSV files declared in the manifest

  • Check scss-css-import

An @import of a stylesheet that is not part of the bundle: @import url(...), an @import of an http(s):// or // address, or of a .css file. (Any other @import is a Sass partial that the compiler inlines, it costs nothing and is not reported.)

@import url(...) (and any @import inside a .css file) is left to the browser. The browser does not know about the imported file until it has downloaded and parsed the one that imports it, so the two downloads are chained one after the other instead of running in parallel, and the page cannot paint before both end (GTmetrix: "Avoid CSS @import" and "Avoid chaining critical requests"). When the address is another site, as fonts.googleapis.com, it also costs a new connection (DNS, TCP and TLS), the stylesheet has a short cache lifetime that you do not control, and every visitor is revealed to a third party. Self-host instead: download the font files as .woff2, declare the @font-face in the module with font-display: swap and delete the @import.

A quoted @import "..." of a .css file or of an address, in a .scss file, never reaches the browser: Odoo removes the quoted imports whose path has a dot or starts with ., / or ~, and reports "Local import is forbidden for security reasons" among the errors of the bundle. The file is not loaded at all. List it in the assets of the manifest instead (.css files go in the bundle as they are), or self-host the font as said above.

  • Check scss-font-display-missing

A @font-face without font-display. The browser then uses auto, which in practice is block: the text that uses the font stays invisible until the font arrives, up to 3 seconds, before it falls back (the "flash of invisible text"). That delays the First and Largest Contentful Paint of every page that has text in that font (GTmetrix: "Ensure text remains visible during webfont load").

font-display: swap paints the text at once with the fallback font and swaps it when the font is ready. Prefer optional for a decorative font that may be skipped on a slow connection, because it never moves the text (no layout shift). An icon font needs block: while it downloads the browser must wait for it, because a fallback font paints the code points of the icons as unrelated characters.

The stylesheets of the PDF report bundles are not reported: wkhtmltopdf does not paint the text progressively, so font-display has no effect there.

The autofix adds font-display: swap; as the last declaration of the @font-face.

  • Check scss-font-legacy-format

A @font-face serves its font as .otf, .ttf, .eot or .woff and no .woff2. WOFF2 compresses the font with Brotli: the same font weighs about 50-70 % less than the .ttf/.otf (an uncompressed container made for the desktop) and about 20-30 % less than .woff (zlib). Every browser still supported reads it (Chrome 36, Firefox 39, Safari 12, Edge 14), so no other format is needed as a fallback in a browser (wkhtmltopdf does not read WOFF2, so the stylesheets of the report bundles are skipped). With the default font-display the text stays invisible while the font downloads, so its size shows in the First and Largest Contentful Paint (GTmetrix: "Enormous network payloads").

To migrate a font keep its glyphs and convert only the container: pip install fonttools brotli && fonttools ttLib.woff2 compress Font.otf (or woff2_compress Font.otf), commit the new .woff2, point the url() to it with format("woff2") and delete the old file. Convert .eot and .svg fonts from the original .ttf/.otf.

Only the stylesheets that the manifest lists in assets are read: a Sass partial that is only reached through an @import, a .sass or .less file is not. The stylesheets of the PDF report bundles are not reported (the bundle is read from the assets of the manifest: web.report_assets_common, web.report_assets_pdf, snailmail.report_assets_snailmail...). wkhtmltopdf renders them with an old QtWebKit that cannot read WOFF2, so their fonts must stay as .ttf or .otf.

The autofix rewrites the url() and its format() when the .woff2 is already next to the old file. It does not convert the font: the conversion is a binary file that has to be reviewed and committed.

  • Check xml-deprecated-data-node Deprecated node inside xml node

  • Check xml-deprecated-oe-chatter

Odoo 18 introduced a new XML tag <chatter/> which replaces the old way to declare chatters on form views. For more information, see: odoo/odoo#156463

  • Check xml-deprecated-openerp-node deprecated xml node

  • Check xml-deprecated-qweb-directive for use of deprecated QWeb directives t-*-options

  • Check xml-deprecated-qweb-directive-15 t-esc and t-raw directives are deprecated in Odoo v15.0, use t-out instead. For more details https://github.com/odoo/odoo/commit/01875541b1a8131cb and odoo/odoo#70004

  • Check xml-deprecated-res-groups-category-id

Odoo 19 removed the field category_id of res.groups. It was replaced by privilege_id, a many2one to the new model res.groups.privilege, so a record still writing category_id breaks the installation with ValueError: Invalid field 'category_id' on model 'res.groups'. The autofix removes the field, the very change Odoo applied to its own groups whose category was only a technical one. Set privilege_id by hand instead when the group is meant to be displayed under a privilege in the user form. For more details https://github.com/odoo/odoo/commit/33637d137ed52f5faabaafd5c208e187042be8eb and odoo/odoo#199988

  • Check xml-header-missing Generated when the XML file is missing the XML declaration header ''

  • Check xml-header-wrong Generated when the XML file declaration header is different than expected (case sensitive).

  • Check xml-img-without-size

The <img> tag of a QWeb template has no width and height attributes. The browser reserves no space for the picture until it arrives, so everything below it moves when it does (Cumulative Layout Shift, reported by Lighthouse and GTmetrix as "Use explicit width and height on image elements"). Use the intrinsic size of the image in pixels: with img-fluid or height: auto the picture still scales down with its container, but the width attribute is the width that it uses, so a smaller number than the real one shrinks the picture. The dynamic forms t-att-width, t-attf-width, t-att and t-att-style, a width and a height in the inline style and an inline aspect-ratio are accepted too. Images of a t-field or t-out widget, whose tag is built by Odoo, and the QWeb views declared in the arch of an ir.ui.view record are not seen here.

The picture is not reported where stating its size is useless or harmful:

  • a PDF report or a mail: the template inherits or calls a report or mail layout (web.external_layout*, web.html_container, mail.*, mass_mailing.*), it is the template of an ir.actions.report of the module, or its file is in a report/ directory or has mail, mailing or digest in its name

  • content that the user replaces in the website builder: a picture with a fixed src inside a data-snippet, an oe_structure/o_editable zone, a snippet template (s_*) or a page template. A picture whose src is built by the template (t-att-src, t-attf-src: the logo of the website, the photo of a record) is still reported

  • a size already fixed by the class (o_image_64_cover) or by width and height in the inline style, a picture out of the flow (position-absolute, position: absolute) and a pixel inside <noscript> Anything else can be silenced with the usual comment of the file.

  • Check xml-not-valid-char-link The resource in in src/href contains a not valid character.

  • Check xml-oe-structure-missing-id

Ensure all tags with class 'oe_structure' have an ID. For more information on the rationale, see: #27

  • Check xml-redundant-module-name

If the module is called "module_a" and the xmlid is <record id="module_a.xmlid_name1" ...

The "module_a." is redundant it could be replaced to only <record id="xmlid_name1" ...

  • Check xml-field-bool-without-eval

if the record is boolean but without eval attribute <field name="active">True</field> instead of <field name="active" eval="True" />

  • Check xml-field-numeric-without-eval

if the record is integer but without eval attribute <field name="sequence">100</field> instead of <field name="sequence" eval="100" />

  • Check xml-invisible-in-list-view

Using invisible="1" or invisible="True" on a <field> inside a <list> or <tree> view does not hide the column properly. Since Odoo 17 the correct attribute to hide an entire column is column_invisible="True". For more details see https://www.odoo.com/documentation/17.0/developer/reference/backend/views.html#lists

Only the columns, the fields that are direct children of the <list> or <tree>, are checked, so the ones added by an inherited view (<xpath ... position="inside">, <attribute name="invisible">) are not reported. A field of a view declared inside a field of the list (<form>, <kanban>, ...) or of a <groupby> is not reported either.

The autofix replaces invisible="1" and invisible="True" with column_invisible="True". The column is then removed as a whole: its header, its footer total and its export are gone too, instead of only emptying the cell of each row. It is skipped (the error is still reported) when the field already has column_invisible.

  • Check xml-create-user-wo-reset-password records of user without context="{'no_reset_password': True}" This context avoid send email and mail log warning

  • Check xml-view-dangerous-replace-low-priority in ir.ui.view

    ...
  • Check xml-deprecated-tree-attribute The tree-view declaration is using a deprecated attribute.

  • Check xml-record-missing-id Generated when a tag has no id.

  • Check xml-duplicate-record-id

If a module has duplicated record_id AKA xml_ids file1.xml <record id="xmlid_name1" file2.xml <record id="xmlid_name1"

  • Check xml-duplicate-fields in all record nodes <record id="xmlid_name1"... <field name="field_name1"... <field name="field_name1"...

  • Check xml-syntax-error Check syntax of XML files declared in the Odoo manifest

  • Check xml-tag-position Check the position of XML attributes. The order is dynamically configurable via xml_attributes_order.

  • Check xml-dangerous-qweb-replace-low-priority Dangerous qweb view defined with low priority

  • Check xml-duplicate-template-id Triggered when two templates share the same ID

  • Check xml-xpath-translatable-item check xpath nodes using contains(text(), 'Text translatable') Since that the text could be translated so it is a mutable value. It could raise ValueError exception if the language is changed.

** Special fixit checks

  • Check field-string-redundant Detects and removes the 'string' parameter in odoo.fields if it is redundant (matches the field name in Title Case), ensuring it only applies to Odoo Class definitions (Models).

  • Check manifest-superfluous-key Identifies and removes Identifies from Odoo manifest files (manifest.py) superfluous keys (if they have the same as the default value) should be omitted for simplicity

e.g. 'installable': True True is the default value for installable key

e.g. 'data': [] [] is the default value for 'data' key

  • Check prefer-env-translation Replace _('text') with self.env._('text') only if '' comes from 'odoo.' and only for modules >=18.0

  • Check unused-logger Disallow unused _logger = logging.getLogger(__name__) in Odoo models.

Checks PO

  • Check po-requires-module Translation entry requires comment #. module: MODULE

  • Check po-python-parse-printf Check if msgid is using str variables like %s So translation msgstr must be the same number of variables too

  • Check po-python-parse-format Check if msgid is using str variables like {} So translation msgstr must be the same number of variables too

  • Check po-duplicate-message-definition (message-id) in all entries of PO files

  • Check po-duplicate-model-definition Verify that no entries share the same 'model:' tag

  • Check po-pretty-format Check the following:

  1. Entries sorted alphabetically
  2. Lines are wrapped at 78 columns (same as Odoo)
  3. Clear msgstr when it is the same as msgid
  • Check po-syntax-error Check syntax of PO files from i18n* folders

Help

usage: oca-checks-odoo-module [-h] [--no-verbose] [--no-exit] [--disable DISABLE] [--enable ENABLE] [--config CONFIG] [--list-msgs] [--fix] [--xml-attributes-order XML_ATTRIBUTES_ORDER] [files_or_modules ...]

positional arguments:
 files_or_modules Odoo __manifest__.py paths or Odoo module paths.

options:
 -h, --help show this help message and exit
 --no-verbose If enabled so disable verbose mode.
 --no-exit If enabled so it will not call exit.
 --disable, -d DISABLE Disable the checker with the given 'check-name', separated by commas.
 --enable, -e ENABLE Enable the checker with the given 'check-name', separated by commas. Default: All checks are enabled by default
 --config, -c CONFIG Path to a configuration file (default: .oca_hooks.cfg)
 --list-msgs List all currently enabled messages.
 --fix Automatically fix files when possible
 --xml-attributes-order XML_ATTRIBUTES_ORDER Define a group of XML attributes to order with priority, comma-separated values. Repeat this option to add multiple groups. Example: --xml-attributes-order=t-if,t-else --xml-attributes-order=id,t-att-id --xml-attributes-order=class

Help PO

usage: oca-checks-po [-h] [--no-verbose] [--no-exit] [--disable DISABLE] [--enable ENABLE] [--config CONFIG] [--list-msgs] [--fix] [--xml-attributes-order XML_ATTRIBUTES_ORDER] [po_files ...]

positional arguments:
 po_files PO files.

options:
 -h, --help show this help message and exit
 --no-verbose If enabled so disable verbose mode.
 --no-exit If enabled so it will not call exit.
 --disable, -d DISABLE Disable the checker with the given 'check-name', separated by commas.
 --enable, -e ENABLE Enable the checker with the given 'check-name', separated by commas. Default: All checks are enabled by default
 --config, -c CONFIG Path to a configuration file (default: .oca_hooks.cfg)
 --list-msgs List all currently enabled messages.
 --fix Automatically fix files when possible
 --xml-attributes-order XML_ATTRIBUTES_ORDER Define a group of XML attributes to order with priority, comma-separated values. Repeat this option to add multiple groups. Example: --xml-attributes-order=t-if,t-else --xml-attributes-order=id,t-att-id --xml-attributes-order=class

Examples

Examples PO

Licenses

This repository is licensed under AGPL-3.0.


OCA, or the Odoo Community Association, is a nonprofit organization whose mission is to support the collaborative development of Odoo features and promote its widespread use.

About

Linters of Odoo addons that complement pylint-odoo

Resources

Code of conduct

Contributing

Security policy

Stars

26 stars

Watchers

18 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages