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
Translation patch for Hololive ERROR

Translation patch for Hololive ERROR How do I install the patch? Grab the Translation.zip file for the latest version from the releases page, and unzi

18 Jul 20, 2022
Amazon SageMaker Delta Sharing Examples

This repository contains examples and related resources showing you how to preprocess, train, and serve your models using Amazon SageMaker with data fetched from Delta Lake.

Eitan Sela 5 May 02, 2022
A simple hash system.

PBH-Hash-System A simple hash system. Usage You could use it like this: from pbh import pbh print(pbh("Hey", True)) Output: 2feae2471698cfcdcbd6b98ca

Karim 3 Mar 24, 2022
Convert three types of color in your clipboard and paste it to the color property (gamma correct)

ColorPaster [Blender Addon] Convert three types of color in your clipboard and paste it to the color property (gamma correct) How to Use Hover your mo

13 Oct 31, 2022
Beancount Importers for DKB (Deutsche Kredit Bank) CSV Exports

Beancount DKB Importer beancount-dkb provides an Importer for converting CSV exports of DKB (Deutsche Kreditbank) account summaries to the Beancount f

Siddhant Goel 24 Aug 06, 2022
This script provides LIVE feedback for On-The-Fly data collection with RELION

README This script provides LIVE feedback for On-The-Fly data collection with RELION (very useful to explore already processed datasets too!) Creating

cryoEM CNIO 6 Jul 14, 2022
It's an .exe file that can notify your chia profit and warning message every time automatically.

chia-Notify-with-Line 警示程式 It's an .exe file that can notify your chia profit and warning message every time automatically. 這是我自行設計的小程式,有轉成.exe檔了,可以在沒

You,Yu 1 Oct 28, 2021
Purge your likes and wall comments from VKontakte. Set yourself free from your digital footprint.

vk_liberator Regain liberty in the cruel social media world. This program assists you with purging your metadata from Russian social network VKontakte

20 Jun 11, 2021
Penelope Shell Handler

penelope Penelope is an advanced shell handler. Its main aim is to replace netcat as shell catcher during exploiting RCE vulnerabilities. It works on

293 Dec 30, 2022
A programming language that for tech savvy graphic designers

Microsoft Hackathon - PhoTex Idea A programming language that allows tech savvy graphic designers develop scalable vector graphics using plain text co

Joe Furfaro 5 Nov 14, 2021
Osintgram by Datalux but i fixed some errors i found and made it look cleaner

OSINTgram-V2 OSINTgram-V2 is made from Osintgram which is made by Datalux originally but i took the script and fixed some errors i found and made the

2 Feb 02, 2022
A simple bot that will help you in your learning and make it more fun.

hyperskill-SimpleChattyBot-python A simple bot that will help you in your learning and make it more fun. Syntax bot.py Stages Stage #1: Zuhura Bot we

1 Nov 09, 2021
python scripts and other files to generate induction encoder PCBs in Kicad

induction_encoder python scripts and other files to generate induction encoder PCBs in Kicad Targeting the Renesas IPS2200 encoder chips.

Taylor Alexander 8 Feb 16, 2022
BlackIP-Rep is a tool designed to gather the reputation and information of Bulk IP's.

BlackIP-Rep is a tool designed to gather the reputation and information of Bulk IP's. Focused on increasing the workflow of Security Operations(SOC) team during investigation.

0LiVEr 6 Dec 12, 2022
MIB2 STD ZR Firmware Upgrade

Upgrade MIB2 STD ZR Firmware (without Navigation) About This repository contains some scripts and documentation how to upgrade the MIB2 firmware to a

Fabian 18 Dec 29, 2022
Snek-test - An operating system kernel made in python and assembly

pythonOS An operating system kernel made in python and assembly Wait what? It us

TechStudent10 2 Jan 25, 2022
A framework to create reusable Dash layout.

dash_component_template A framework to create reusable Dash layout.

The TolTEC Project 4 Aug 04, 2022
Integration of Hotwire's Turbo library with Flask.

turbo-flask Integration of Hotwire's Turbo library with Flask, to allow you to create applications that look and feel like single-page apps without us

Miguel Grinberg 240 Jan 06, 2023
Fast Base64 encoding/decoding in Python

Fast Base64 implementation This project is a wrapper on libbase64. It aims to provide a fast base64 implementation for base64 encoding/decoding. Insta

Matthieu Darbois 96 Dec 26, 2022
Google Foobar challenge solutions from my experience and other's on the web.

Google Foobar challenge Google Foobar challenge solutions from my experience and other's on the web. Note: Problems indicated with "Mine" are tested a

Islam Ayman 6 Jan 20, 2022