A Regex based linter tool that works for any language and works exclusively with custom linting rules.

Related tags

Miscellaneousrenag
Overview

renag

TravisCI Build Status codecov

Documentation Available Here

Short for Regex (re) Nag (like "one who complains").

Now also PEGs (Parsing Expression Grammars) compatible with pyparsing!

A Regex based linter tool that works for any language and works exclusively with custom linting rules.

Complainers

renag is based on the concept of Complainers. See renag/complainer.py for the interface to create your own Complainer and examples for some prebuilt examples.

Complainers can be as simple as the following:

class PrintComplainer(Complainer):
    """Print statements can slow down code."""

    capture = r"print\(.*\)"
    severity = Severity.WARNING
    glob = ["*.py"]

This has 4 fundamental parts:

  • docstring - The docstring of the class automatically becomes the description of the error.
  • capture - A regex statement that, if matched, will raise the complaint.
  • severity - Either WARNING which will return exit code 0, or CRITICAL which will return exit code 1.
  • glob - A list of glob wildcards that define what files to run the Complainer on.

Next you can add a check method to your Complainer if you would like something more complicated than simple regex.

class PrintComplainer(Complainer):
    """Print statements can slow down code."""
    ...

    def check(self, txt: str, path: Path, capture_span: Span) -> List[Complaint]:
          """Check that the print statement is not commented out before complaining."""
          # Get the line number
          lines, line_numbers = get_lines_and_numbers(txt, capture_span)

          # Check on the first line of the capture_span that the capture is not preceded by a '#'
          # In such a case, the print has been commented out
          if lines[0].count("#") > 0 and lines[0].index("#") < capture_span[0]:

              # If it is the case that the print was commented out, we do not need to complain
              # So we will return an empty list of complaints
              return []

          # Otherwise we will do as normal
          return super().check(txt=txt, path=path, capture_span=capture_span)

Adding to your project

Simply put this complainer in a python module in your project like so:

root/
  complainers_dir_name/
    __init__.py
    custom_complainer1.py
    custom_complainer2.py
    ...
  the-rest-of-your-project
  ...

Import each complainer inside __init__.py so it can be imported via from .{complainers_dir_name} import *.

Then add the following to your .pre-commit-hooks.yaml file:

- repo: https://github.com/ryanpeach/renag
  rev: "0.3.4"
  hooks:
    - id: renag
      args:
        - "--load_module"
        - "{complainers_dir_name}"
        - "--staged"

Run renag --help to see a list of command line arguments you can add to the hook.

Output

Complaint printout modeled after rust error reporting. Example of a Complaint:

Severity.WARNING - EasyPrintComplainer: Print statements can slow down code.
  --> renag/__main__.py
   147|                                 )
   148|                                 print()
   149|
   150|     # End by exiting the program
   151|     if N == 0:
   152|         print(color_txt("No complaints. Enjoy the rest of your day!", BColors.OKGREEN))
   152|         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   153|         exit(0)
   154|     if N_WARNINGS > 0 and N_CRITICAL == 0:
   155|         print(
   156|             color_txt(
   157|                 f"{N} Complaints found: {N_WARNINGS} Warnings, {N_CRITICAL} Critical.",

iregex

All regex captures in this module default to using iregex. iregex can help make your regex more understandable to readers, and allow you to compose large regex statements (see examples/regex.py for examples).

You might also like...
Python script to autodetect a base set of swiftlint rules.

swiftlint-autodetect Python script to autodetect a base set of swiftlint rules. Installation brew install pipx

Bazel rules to install Python dependencies with Poetry

rules_python_poetry Bazel rules to install Python dependencies from a Poetry project. Works with native Python rules for Bazel. Getting started Add th

This library attempts to abstract the handling of Sigma rules in Python

This library attempts to abstract the handling of Sigma rules in Python. The rules are parsed using a schema defined with pydantic, and can be easily loaded from YAML files into a structured Python object.

Advent of Code is an Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

Advent Of Code 2021 - Python English Advent of Code is an Advent calendar of small programming puzzles for a variety of skill sets and skill levels th

Learn to code in any language. If

Learn to Code It is an intiiative undertaken by Student Ambassadors Club, Jamshoro for students who are absolute begineers in programming and want to

Free Vocabulary Trainer - not only for German, but any language
Free Vocabulary Trainer - not only for German, but any language

Bilderraten DOWNLOAD THE EXE FILE HERE! What can you do with it? Vocabulary Trainer for any language Use your own vocabulary list No coding required!

Animation retargeting tool for Autodesk Maya. Retargets mocap to a custom rig with a few clicks.
Animation retargeting tool for Autodesk Maya. Retargets mocap to a custom rig with a few clicks.

Animation Retargeting Tool for Maya A tool for transferring animation data between rigs or transfer raw mocap from a skeleton to a custom rig. (The sc

A community based economy bot with python works only with python 3.7.8 as web3 requires cytoolz

A community based economy bot with python works only with python 3.7.8 as web3 requires cytoolz has some issues building with python 3.10

Comments
  • Fixes to main branch + fixes to previously merged features

    Fixes to main branch + fixes to previously merged features

    List of changes:

    • Added --inline flag which hides an error line when the number of lines to show is set to 0. Since it's an offset for additional lines IMO 0 should still show the line with an error itself. At least I need this feature, if you don't like it, use the --inline flag, when setting number of additional lines to 0;
    • Fix to previously merged 'finalize' feature;
    • Fix for the empty regex warning, fixed an issue that complainers were mapped to regex string, but than tried to access them through Regex object (#6);
    • Fix to module imports
    • and some more (please, refer to commit messages)

    P.S.: Even though module import seems to be fixed and is working as of now, I still couldn't manage to make renag pre-commit hook to import module properly, so had to remove the __init__.py file. P.S. 2: There are still issues with examples folder and examples in the readme, but I really don't feel like fixing it as of today.

    opened by kittyandrew 2
  • Need a way to preprocess code so it can be used as a unit test without proprietary information being leaked

    Need a way to preprocess code so it can be used as a unit test without proprietary information being leaked

    If it matches the expression, let it pass as is, otherwise if it's an alpha character replace it with alpha, if it's numeric replace it with numeric. Functionality is not preserved, but form is. Then check that the same match is returned.

    opened by ryanpeach 0
  • Is a directory

    Is a directory

    Traceback (most recent call last):
      File "/usr/local/bin/renag", line 8, in <module>
        sys.exit(main())
      File "/usr/local/lib/python3.7/site-packages/renag/__main__.py", line 208, in main
        with file2.open("r") as f2:
      File "/usr/local/Cellar/[email protected]/3.7.12_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/pathlib.py", line 1208, in open
        opener=self._opener)
    IsADirectoryError: [Errno 21] Is a directory: '/Users/.../Documents/Workspace/.../.git/objects/00'
    
    opened by ryanpeach 5
Releases(0.4.4)
  • 0.4.4(Oct 16, 2021)

    Changes from @kittyandrew

    • Added --inline flag which hides an error line when the number of lines to show is set to 0. Since it's an offset for additional lines IMO 0 should still show the line with an error itself. At least I need this feature, if you don't like it, use the --inline flag, when setting number of additional lines to 0;
    • Fix to previously merged 'finalize' feature;
    • Fix for the empty regex warning, fixed an issue that complainers were mapped to regex string, but than tried to access them through Regex object (This is not working for regex for some reason. #6);
    • Fix to module imports
    • and some more (please, refer to commit messages)
    Source code(tar.gz)
    Source code(zip)
Owner
Ryan Peach
Machine Learning Researcher at Keysight Technologies in Atlanta GA. Electrical Engineering BS Machine Learning MS
Ryan Peach
UF3: a python library for generating ultra-fast interatomic potentials

Ultra-Fast Force Fields (UF3) S. R. Xie, M. Rupp, and R. G. Hennig, "Ultra-fast interpretable machine-learning potentials", preprint arXiv:2110.00624

Ultra-Fast Force Fields 24 Nov 13, 2022
Write a program that works out whether if a given year is a leap year

Leap Year 💪 This is a Difficult Challenge 💪 Instructions Write a program that works out whether if a given year is a leap year. A normal year has 36

Rodrigo Santos 0 Jun 22, 2022
Autogenerador tonto de paquetes para ROSCPP

Autogenerador tonto de paquetes para ROSCPP Autogenerador de paquetes que usan C++ en ROS. Por ahora tiene las siguientes capacidades: Permite crear p

1 Nov 26, 2021
Neogex is a human readable parser standard, being implemented in Python

Neogex (New Expressions) Parsing Standard Much like Regex, Neogex allows for string parsing and validation based on a set of requirements. Unlike Rege

Seamus Donnellan 1 Dec 17, 2021
Petuhlang is a joke-like language, based on Python.

Petuhlang is a joke-like language, based on Python. It updates builtins to make a new syntax based on operators rewrite.

DenyS 9 Jun 19, 2022
A replacement of qsreplace, accepts URLs as standard input, replaces all query string values with user-supplied values and stdout.

Bhedak A replacement of qsreplace, accepts URLs as standard input, replaces all query string values with user-supplied values and stdout. Works on eve

Eshan Singh 84 Dec 31, 2022
🟥This is an overview of how to set up and use DataStore3 in your Roblox experiences

Welcome to DataStore3 👋 This is an overview of how to set up and use DataStore3 in your Roblox experiences What is it? 🤔 DataStore3 is a service tha

Reece Harris 7 Aug 19, 2022
Custom component to calculate estimated power consumption of lights and other appliances

Custom component to calculate estimated power consumption of lights and other appliances. Provides easy configuration to get virtual power consumption sensors in Home Assistant for all your devices w

Bram Gerritsen 552 Dec 28, 2022
The git for the Python Story Utility Package library.

PSUP, The Python Story Utility Package Module. PSUP helps making stories or games with options, diverging paths, different endings and so on. You can

Enoki 6 Nov 27, 2022
Korg Volca Sample uploader for linux.

GnuVolca Korg Volca Sample uploader for linux. GnuVolca Usage Installation Via virtualenv Usage Store all the samples you want to upload on an empty d

Gonzalo Rafuls 12 Oct 11, 2022
Very Simple 2 Message Spammer!

Very Simple 2 Message Spammer!

Syntax. 4 Dec 06, 2022
The CS Netlogo Helper is a small python script I made, to make computer science homework easier.

The CS Netlogo Helper is a small python script I made, to make computer science homework easier. This project is really ironic now that I think about it.

1 Jan 13, 2022
Utility/Raiding selfbot made by Shell and Roover.

Utility/Raiding selfbot made by Shell and Roover. We are open to suggestions and ideas.

Shell 2 Dec 08, 2021
Algo próximo do ARP

ArpPY Algo parecido com o ARP-Scan. Dependencias O script necessita no mínimo ter o Python versão 3.x instalado e ter o sockets instalado. Executando

Feh's 3 Jan 18, 2022
A deployer and package manager for OceanBase open-source software.

OceanBase Deploy OceanBase Deploy (简称 OBD)是 OceanBase 开源软件的安装部署工具。OBD 同时也是包管理器,可以用来管理 OceanBase 所有的开源软件。本文介绍如何安装 OBD、使用 OBD 和 OBD 的命令。 安装 OBD 您可以使用以下方

OceanBase 59 Dec 27, 2022
An implementation of an interpreter for the Brainfuck esoteric language in Python

Brainfuck Interpreter in Python An implementation of an interpreter for the Brainfuck esoteric language in Python. 🧠 The Brainfuck Language Created i

Carlos Santos 0 Feb 01, 2022
A Brainfuck interpreter written in Python.

A Brainfuck interpreter written in Python.

Ethan Evans 1 Dec 05, 2021
A Lego Mindstorm robot for dealing out cards based on a birds-eye view of a poker table and given ArUco fiducial tags.

A Lego Mindstorm robot for dealing out cards based on a birds-eye view of a poker table and given ArUco fiducial tags.

4 Dec 06, 2021
My custom Fedora ostree build with sway/wayland.

Ramblurr's Sway Desktop This is an rpm-ostree based minimal Fedora developer desktop with the sway window manager and podman/toolbox for doing develop

Casey Link 1 Nov 28, 2021
A telegram bot which programed to countdown.

countdown-vi this is a telegram bot which programed to countdown. usage well, first you should specify a exact interval. there is 5 column, very first

Arya Shabane 3 Feb 15, 2022