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
A step-by-step tutorial for how to work with some of the most basic features of Nav2 using a Jupyter Notebook in a warehouse environment to create a basic application.

This project has a step-by-step tutorial for how to work with some of the most basic features of Nav2 using a Jupyter Notebook in a warehouse environment to create a basic application.

Steve Macenski 49 Dec 22, 2022
Encode and decode cancro lang files to and from brainfuck

cancrolang Encode and decode cancro lang files to and from brainfuck. examples python3 main.py -f hello.cancro --run Hello World! the interpreter is n

witer33 1 Dec 20, 2021
Decoupled Smoothing in Probabilistic Soft Logic

Decoupled Smoothing in Probabilistic Soft Logic Experiments for "Decoupled Smoothing in Probabilistic Soft Logic". Probabilistic Soft Logic Probabilis

Kushal Shingote 1 Feb 08, 2022
Simple cash register system made with guizero

Eje-Casher なにこれ guizeroで作った簡易レジシステムです。実際にコミケで使う予定です。 これを誰かがそのまま使うかどうかというよりは、guiz

Akira Ouchi 4 Nov 07, 2022
Chemical Analysis Calculator, with full solution display.

Chemicology Chemical Analysis Calculator, to solve problems efficiently by displaying whole solution. Go to releases for downloading .exe, .dmg, Linux

Muhammad Moazzam 2 Aug 06, 2022
Resizing using nnedi3/znedi3/nnedi3cl with center alignment and correct chroma placement

nnedi3_resample A VapourSynth script for easy resizing using nnedi3/znedi3/nnedi3cl with center alignment and correct chroma placement. Requirements n

Home Of VapourSynth Evolution 12 Sep 08, 2022
This is the Halloween edition of my Flask Greeting App - HAPPY HALLOWEEEN EVERYONE! :)

HalloweenGreetingApp HAPPY HALLOWEEN EVERYONE! :) This is the Halloween Edition of my Flask Greeting App! Please note, this application is mean to be

Mariya 2 Feb 04, 2022
A python script that changes your desktop background based on current weather and time of the day.

Desktop background wallpaper, based on current weather and time A python script that changes your computer's desktop background based on current weath

Maj Gaberšček 1 Nov 16, 2021
E5自动续期

AutoApi v6.3 (2021-2-18) ———— E5自动续期 AutoApi系列: AutoApi(v1.0) 、 AutoApiSecret(v2.0) 、 AutoApiSR(v3.0) 、 AutoApiS(v4.0) 、 AutoApiP(v5.0) 说明 E5自动续期程序,但是

34 Feb 20, 2021
Viewer for NFO files

NFO Viewer NFO Viewer is a simple viewer for NFO files, which are "ASCII" art in the CP437 codepage. The advantages of using NFO Viewer instead of a t

Osmo Salomaa 114 Dec 29, 2022
A python program for rick rolling people.

Rickware A python program for rick rolling people. (And annoying them too) What is rick roll? Read this wikipedia article - Rickrolling About program

2 Jan 18, 2022
Async Python Circuit Breaker implementation

aiocircuitbreaker This is an async Python implementation of the circuitbreaker library. Installation The project is available on PyPI. Simply run: $ p

5 Sep 05, 2022
Anki for desktop computers

Anki This repo contains the source code for the computer version of Anki. If you'd like to try development builds of Anki but don't feel comfortable b

Ankitects 12.9k Jan 09, 2023
People tracker on the Internet: OSINT analysis and research tool by Jose Pino

trape (stable) v2.0 People tracker on the Internet: Learn to track the world, to avoid being traced. Trape is an OSINT analysis and research tool, whi

Jose Pino 7.3k Dec 30, 2022
Dotfiles & list of programs

dotfiles & list of programs So I wanted to just backup my most used files. I have a bad habit, sometimes I get tired of a distro and do a wipe and sta

2 Sep 04, 2022
Data Structures and Algorithms Python - Practice data structures and algorithms in python with few small projects

Data Structures and Algorithms All the essential resources and template code nee

Hesham 13 Dec 01, 2022
Скрипт позволяет заводить задачи в Панель мониторинга YouTrack на основе парсинга сайта safe-surf.ru

Скрипт позволяет заводить задачи в Панель мониторинга YouTrack на основе парсинга сайта safe-surf.ru

Bad_karma 3 Feb 12, 2022
System Design Assignments as part of Arpit's System Design Masterclass

System Design Assignments The repository contains a set of problem statements around Software Architecture and System Design as conducted by Arpit's S

Relog 1.1k Jan 09, 2023
A dog facts python module

A dog facts python module

Fayas Noushad 3 Nov 28, 2021
Repositório do Projeto de Jogo da Resília Educação.

Jogo da Segurança das Indústrias Acme Descrição Este jogo faz parte do projeto de entrega do primeiro módulo da Resilia Educação, referente ao curso d

Márcio Estevam da Silva 2 Apr 28, 2022