Chasten checks the AST of a Python program!
Project description
๐ซ chasten
๐ Introduction
-
Chasten is a Python program that uses XPath expressions to find patterns in the abstract syntax tree (AST) of a Python program. You can use Chasten to quickly implement your own configurable linting rules, without having to use a complex AST analysis framework or resorting to imprecise regular expressions.
-
Do you want to ensure that a Python program has does not have any triple-nested
for
loops inside ofasync
functions? Or, do you want to confirm that every function inside your Python program has type annotations and a docstring comment? Chasten can help! It allows you to express these checks โ and many other types of analyses as well โ in simple YAML files that contain XPath expressions.
๐ Definitions
-
chasten (transitive verb) "to make someone aware of failure or of having done something wrong", Cambridge Dictionary.
- Example Sentence: "Her remarks are a gift to me even as they chasten and redirect my efforts to expand the arguments of this book into a larger one.", Cambridge English Corpus
-
chasten (uncountable or singular noun) "a tool that analyzes the abstract syntax tree of a Python program to detect potential sources of programmer mistakes so as to prevent program failure", AstuteSource Developers.
- Student Sentence: "I'm glad that
chasten
reminded me to add docstrings and type annotations to all of the functions inmain.py
. It was easy to see what to fix!" - Instructor Sentence: "
chasten
makes it easy for me to reliably confirm that student programs have the required coding constructs. It's much better than using regular expressions!" - Developer Sentence: "Since I was already familiar with XPath
expressions,
chasten
made it fun and easy for me to do an automate analysis of a Python codebase that I maintain." - Researcher Sentence: "In addition to helping me quickly scan the
source code of Python projects,
chasten
's analysis dashboard lets me effectively explore the data I collect."
- Student Sentence: "I'm glad that
๐Features
- โจ Easy-to-configure, automated analysis of a Python program's abstract syntax tree
- ๐ Flexible and easy-to-use YAML-based configuration file for describing analyses and checks
- ๐ช Automated generation and verification of the YAML configuration files for an analysis
- ๐ Configurable saving of analysis results in the JSON, CSV, or SQLite formats
- ๐ง Automated integration of result files that arise from multiple runs of the tool
- ๐ Interactive results analysis through the use of a locally running datasette server
- ๐ Automated deployment of a datasette server on platforms like Fly or Vercel
- ๐ฆ Detailed console and syslog logging to furnish insights into the tool's behavior
- ๐ Rich command-line interface with robust verification of arguments and options
- ๐คฏ Interactive command-line generation through an easy-to-use terminal user interface
โก๏ธ Requirements
- Python 3.11
- Chasten leverages numerous Python packages, including notable ones such as:
- Datasette: Interactive data analysis dashboards
- Pyastgrep: XPath-based analysis of a Python program's AST
- Pydantic: Automated generation and validation of configuration files
- Rich: Full-featured formatting and display of text in the terminal
- Trogon: Automated generation of terminal user interfaces for a command-line tool
- Typer: Easy-to-implement and fun-to-use command-line interfaces
- The developers of Chasten use Poetry for packaging and dependency management
๐ฝ Installation
Follow these steps to install the chasten
program:
- Install Python 3.11 for your operating system
- Install pipx to support program installation in isolated environments
- Type
pipx install chasten
to install Chasten - Type
pipx list
and confirm that Chasten is installed - Type
chasten --help
to learn how to use the tool
๐ช Configuration
You can configure chasten
with two YAML files, normally called config.yml
and checks.yml
. Although chasten
can generate a starting configuration, you
can check out the ๐ฆ
AstuteSource/chasten-configuration
repository for example(s) of configuration files that setup the tool. Although
the config.yml
file can reference multiple check configuration files, this
example shows how to specify a single checks.yml
file:
# chasten configuration
chasten:
# point to a single checks file
checks-file:
- checks.yml
The checks.yml
file must contain one or more checks. What follows is an
example of a check configuration file with two checks that respectively find the
first executable line of non-test and test-case functions in a Python project.
Note that the pattern
attribute specifies the XPath version 2.0 expression
that chasten
will use to detect the specified type of Python function. You can
type chasten configure validate --config <path to chasten-configuration/ directory | config url>
after filling in <path to chasten-configuration/directory | config url>
with the
fully-qualified name of your configuration directory and the tool will confirm
that your configuration meets the tool's specification. You can also use the
command chasten configure create
command to automatically generate a starting
configuration! Typing chasten configure --help
will explain how to configure
the tool.
checks:
- name: "all-non-test-function-definition"
code: "FUNC"
id: "FUNC001"
description: "First executable line of a non-test function, skipping over docstrings and/or comments"
pattern: '//FunctionDef[not(contains(@name, "test_"))]/body/Expr[value/Constant]/following-sibling::*[1] | //FunctionDef[not(contains(@name, "test_"))]/body[not(Expr/value/Constant)]/*[1]'
- name: "all-test-function-definition"
code: "FUNC"
id: "FUNC002"
description: "First executable line of a test function, skipping over docstrings and/or comments"
pattern: '//FunctionDef[starts-with(@name, "test_")]/body/Expr[value/Constant]/following-sibling::*[1] | //AsyncFunctionDef[starts-with(@name, "test_")]/body/Expr[value/Constant]/following-sibling::*[1] | //FunctionDef[starts-with(@name, "test_")]/body[not(Expr/value/Constant)]/*[1] | //AsyncFunctionDef[starts-with(@name, "test_")]/body[not(Expr/value/Constant)]/*[1]'
count:
min: 1
max: 10
โจ Analysis
Since chasten
needs a project with Python source code as the input to its
analysis
sub-command, you can clone the
๐ฆ AstuteSource/lazytracker and
๐ฆ AstuteSource/multicounter
repositories that are forks of existing Python projects created for convenient
analysis. To incrementally analyze these two projects with chasten
, you can
type the following commands to produce a results JSON file for each project:
- After creating a
subject-data/
directory that contains alazytracker/
directory, you can run thechasten analyze
command for thelazytracker
program:
chasten analyze lazytracker \
--config <path to the chasten-configuration/ directory | config url> \
--search-path <path to the lazytracker/ directory> \
--save-directory <path to the subject-data/lazytracker/ directory> \
--save
-
Now you can scan the output to confirm that, for instance,
chasten
finds6
test functions in thelazytracker
project. If you look in thesubject-data/lazytracker
directory you will find a JSON file with a name likechasten-results-lazytracker-20230823162341-4c23fc443a6b4c4aa09886f1ecb96e9f.json
. Runningchasten
on this program more than once will produce a new results file with a different timestamp (i.e.,20230823162341
) and unique identifier (i.e.,4c23fc443a6b4c4aa09886f1ecb96e9f
) in its name, thus ensuring that you do not accidentally write over your prior results when using--save
. -
After creating a
multicounter/
directory in the existingsubject-data/
directory, you can run thechasten analyze
command for themulticounter
program:
chasten analyze multicounter \
--config <path to the chasten-configuration/ directory | config url> \
--search-path <path to the multicounter/ directory> \
--save-directory <path to the subject-data/lazytracker/ directory> \
--save
-
Now you can scan the output to confirm that, as an example,
chasten
finds10
test functions in themulticounter
project. If you look in thesubject-data/lazytracker
directory you will find a JSON file with a name likechasten-results-multicounter-20230821171712-5c52f2f1b61b4cce97624cc34cb39d4f.json
and name components that are similar to the JSON file created for themulticounter
program. -
Since the
all-test-function-definition
check specifies that the program must have between1
and10
tests you will notice that this check passes for bothlazytracker
andmulticounter
. This means thatchasten
returns a0
error code to communicate to your operating system that the check passed. -
You can learn more about how to use the
analyze
sub-command by typingchasten analyze --help
. For instance,chasten
supports the--check-include
and--check-exclude
options that allow you to respectively include and exclude specific checks according to fuzzy matching rules that you can specify for any of a check's attributes specified in thechecks.yml
file.
๐ง Integration
After running chasten
on the lazytracker
and multicounter
programs you can
integrate their individual JSON files into a single JSON file, related CSV
files, and a SQLite database. Once you have made an integrated-data/
directory, you can type this command to perform the integration:
chasten integrate all-programs \
<path to subject-data>/**/*.json \
--save-directory <path to the integrated-data/ directory>
This command will produce a directory like
chasten-flattened-csvs-sqlite-db-all-programs-20230823171016-2061b524276b4299b04359ba30452923/
that contains a SQLite database called chasten.db
and a csv/
directory with
CSV files that correspond to each of the tables inside of the database.
You can learn more about the integrate
sub-command by typing chasten integrate --help
.
๐ Verbose Output
When utilizing the chasten
command, appending this --verbose
flag can significantly enhance your troubleshooting experience and provide a detailed understanding of the tool's functionality. Here is an example with chasten analyze lazytracker
:
chasten analyze lazytracker \
--config <path to the chasten-configuration/ directory> \
--search-path <path to the lazytracker/ directory> \
--save-directory <path to the subject-data/lazytracker/ directory> \
--save
--verbose
Upon executing this command, you can expect the output to contain informative messages such as โจ Matching source code:
indicating that the tool is actively comparing the source code against the specified patterns. Additionally, you will receive detailed match results, providing insights into the identified checks.
๐ Results
If you want to create an interactive analysis dashboard that uses ๐ฆ
simonw/datasette you can run chasten datasette-serve <path containing integrated results>/chasten.db --port 8001
.
Now you can use the dashboard in your web browser to analyze the results while
you study the source code for these projects with your editor! Examining the
results will reveal that chasten
, through its use of ๐ฆ
spookylukey/pyastgrep, correctly
uses the XPath expression for all-test-function-definition
to find the first
line of executable source code inside of each test, skipping over a function's
docstring and leading comments.
For the lazytracker
program you will notice that chasten
reports that there
are 6
test cases even though pytest
only finds and runs 5
tests. This is
due to the fact that tests/test_tracked.py
test suite in lazytracker
contains a function starting with test_
inside of another function starting
with test_
. This example illustrates the limitations of static analysis with
chasten
! Even though the tool correctly detected all of the "test functions",
the nesting of the functions in the test suite means that pytest
will run the
outer test_
function and use the inner test_
function for testing purposes.
With that said, chasten
correctly finds each of the tests for the
multicounter
project. You can follow each of the previous steps in this
document to apply chasten
to your own Python program!
๐ Deployment
If you want to make your chasten.db
publicly available for everyone to study,
you can use the chasten datasette-publish
sub-command. As long as you have
followed the installation instructions for ๐ฆ
simonw/datasette-publish-fly
and ๐ฆ
simonw/datasette-publish-vercel,
you can use the plugins to deploy a public datasette
server that hosts your
chasten.db
. For instance, running the command chasten datasette-publish <path containing integrated results>/chasten.db --platform vercel
will publish the
results from running chasten
on lazytracker
and multicounter
to the
Vercel platform.
Importantly, the use of the chasten datasette-publish
command with the
--platform vercel
option requires you to have previously followed the
instructions for the datasette-publish-vercel
plugin to install the vercel
command-line tool. This is necessary because, although
datasette-publish-vercel
is one of chasten
's dependencies neither chasten
nor datasette-publish-vercel
provide the vercel
tool even though they use
it. You must take similar steps before publishing your database to
Fly!
๐คฏ Interaction
Even though chasten
is a command-line application, you create interactively
create the tool's command-line arguments and options through a terminal user
interface (TUI). To use TUI-based way to create a complete command-line for
chasten
you can type the command chasten interact
.
๐Log
Chasten
has a built-in system log. While using chasten you can use the command
chasten log
in your terminal. The system log feature allows the user to see
events and messages that are produced by chasten
. In addition, the chasten log
feature will assist in finding bugs and the events that led to the bug happening.
For the chasten
program to display to the system log you will have to open a
separate terminal and use the command chasten log
. In addition for each command
that is run the --debug-level <choice of level>
and --debug-dest SYSLOG
will
need to be added.
For example, chasten datasette-serve --debug-level DEBUG --debug-dest SYSLOG < database path to file>
will produce the following output in the system log.
๐ซ chasten: Analyze the AST of Python Source Code
๐ GitHub: https://github.com/gkapfham/chasten
โจ Syslog server for receiving debugging information
Display verbose output? False
Debug level? DEBUG
Debug destination? SYSLOG
In each command in chasten
, there is an option to add a --debug-level
. The debug level has 5 options debug, info, warning, error, and critical. Each level will show different issues in the system log where debug is the lowest level of issue from the input where critical is the highest level of error. To leverage more info on this you can reference debug.py
file:
class DebugLevel(str, Enum):
"""The predefined levels for debugging."""
DEBUG = "DEBUG"
INFO = "INFO"
WARNING = "WARNING"
ERROR = "ERROR"
CRITICAL = "CRITICAL"
โจ chasten --help
Usage: chasten [OPTIONS] COMMAND [ARGS]...
โญโ Options โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ --install-completion Install completion for the current shell. โ
โ --show-completion Show completion for the current shell, to copy it or โ
โ customize the installation. โ
โ --help Show this message and exit. โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
โญโ Commands โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ analyze ๐ซ Analyze the AST of Python source code. โ
โ configure ๐ช Manage chasten's configuration. โ
โ datasette-publish ๐ Publish a datasette to Fly or Vercel. โ
โ datasette-serve ๐ Start a local datasette server. โ
โ integrate ๐ง Integrate files and make a database. โ
โ interact ๐ Interactively configure and run. โ
โ log ๐ฆ Start the logging server. โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
๐งโ๐ป Development Enviroment
๐ Local
Follow these steps to install the chasten
tool for future development:
- The development and use of Chasten requires Python 3.11, must be greater or equal to version 3.11.5.
- The developers of Chasten use Poetry for packaging and dependency management.
Once Python and Poetry is installed, please go to the Chasten repository on github and install the tool using the git clone
command in your terminal. Then navigate to the Chasten directory and run the command poetry install
to install all the dependencies.
๐ Docker
There is also the option to use Docker to use chasten
Follow these steps to utilize Docker:
- Install Docker Desktop for your operating system
- Ensure Docker Desktop is running
cd
into the chasten directory where theDockerfile
is located- Type
docker build -t chasten .
to build the container - Type one of the following commands to run the container:
- Windows (Command Prompt) ->
docker run --rm -v "%cd%":/root/src -it chasten
- Windows (Powershell) ->
docker run --rm -v ${pwd}:/root/src -it chasten
- Mac/Ubuntu ->
docker run --rm -v $(pwd):/root/src -it chasten
- Windows (Command Prompt) ->
- Inside the container type
poetry install
- Outside of the container type
docker ps
to view running container information - Outside of the container type
docker commit <your-container-id> <your-image-name>
to save the dependecy installation - Now you can use Docker for all of your
chasten
needs!
๐ Development Tasks
- Linting and Formatting
- We use the linting tools
Black
andRuff
on Chasten to ensure code consistency, readability, and adherence to predefined formatting standards across the entire project, ultimately enhancing maintainability and collaboration among developers. - Please ensure all content in the project follow the appropriate format by running the following commands:
poetry run task fiximports
and/orpoetry run task fixformat
before shipping new features. If features are shipped with linting issues, the build will break on github due to the failure of the test suite.
- We use the linting tools
- Testing and Coverage
- Chasten uses the testing tools
Pytest
andHypothesis
which enables us to fortify code consistency, readability, and alignment with established formatting standards throughout the project. When writing test cases for features, create a new file in the tests directory with the naming conventiontest_(name of file)
. - Please ensure all content in the project passes the tests by running the following commands:
poetry run task test
for most cases or if you would like to test the OpenAI API based featurespoetry run task test-api
before shipping. If features are shipped without a test suite, the coverage will be lowered on github due to the addition of untested code and may potenitally lead to larger issues in the future.
- Chasten uses the testing tools
๐ค Learning
- Curious about the nodes that are available in a Python program's AST?
- Abstract Syntax Tree documentation introduces the nodes of a Python AST
- Green Tea Snakes provides the "missing Python AST docs"
- Textual AST View provides a terminal-based tool for browsing a Python program's AST
- Want to learn more about how to write XPath expressions for a Python AST?
- Pyastgrep offers examples of XPath expressions for querying a Python program's AST
- XPath Documentation describes how to write XPath expressions
- XPath Axes summaries the ways that XPath axes relate a note to other nodes
- Interested in exploring other approaches to querying source code?
- srcML supports XPath-based querying of programs implemented in C, C#, C++, and Java
- Treesitter provides a general-purpose approach to modelling and querying source code
- Python Treesitter offers a Python language bindings for to parsing and querying with Treesitter
๐ค Chasten vs. Symbex
Chasten and Symbex, which was created by Simon Willison, are both tools designed for analyzing Python source code, particularly focusing on searching for functions and classes within files. While they share a common goal, there are notable differences between the two, especially in terms of their command-line interfaces and functionality.
In terms of Command-Line Interface, Symbex employs a concise CLI, utilizing abbreviations for various options. For instance, the command to search for function signatures in a file named test_debug.py
is as follows:
command :symbex -s -f symbex/test_debug.py
def test_debug_level_values():
def test_debug_level_isinstance():
def test_debug_level_iteration():
def test_debug_destination_values():
def test_debug_destination_isinstance():
def test_debug_destination_iteration():
def test_level_destination_invalid():
def test_debug_destination_invalid():
Chasten, on the other hand, leverages Python packages such as Typer and Rich to provide a user-friendly and feature-rich command-line interface. The available commands for Chasten include:
- analyze ๐ซ Analyze the AST of Python source code
- configure ๐ช Manage chasten's configuration
- datasette-publish ๐ Publish a datasette to Fly or Vercel
- datasette-serve ๐ Start a local datasette server
- integrate ๐ง Integrate files and make a database
- interact ๐ Interactively configure and run
- log ๐ฆ Start the logging server.
In terms of functionality, Symbex is designed to search Python code for functions and classes by name or wildcard. It provides the ability to filter results based on various criteria, including function type (async or non-async), documentation presence, visibility, and type annotations.
On the other hand, Chasten's analyze
command performs AST analysis on Python source code. It allows users to specify a project name, XPATH version, search path, and various filtering criteria. Chasten supports checks for inclusion and exclusion based on attributes, values, and match confidence levels. The tool also provides extensive configuration options and the ability to save results in different formats, including markdown.
In summary, while both Chasten and Symbex serve the common purpose of analyzing Python source code, Chasten offers a more versatile and user-friendly CLI with additional features of configuration and result management. Symbex, on the other hand, adopts a concise CLI with a focus on searching and filtering functionalities. The choice between the two tools depends on the user's preferences and specific requirements for Python code analysis.
๐ฆ Similar Tools
In addition to Chasten and Symbex, several other tools offer unique capabilities for analyzing and searching through Python source code, each catering to specific use cases.
- pyastgrep is a tool developed by Luke Plant that provides advanced capabilities for viewing and searching AST using XPath expressions. It allows users to define complex patterns and queries to navigate and extract information from Python code, making it a powerful tool for in-depth code analysis.
- treesitter offers a generic and efficient approach to parsing source code and building AST. It supports multiple languages, providing a consistent API for interacting with parsed code across different language ecosystems.
๐งImprovement
- Found a bug or have a feature that the development team should implement? Raise an issue!
- Interesting in learning more about tool usage details? Check the wiki!
- Want to discuss ways to use the tool? Participate in discussions!
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file chasten-1.0.0.tar.gz
.
File metadata
- Download URL: chasten-1.0.0.tar.gz
- Upload date:
- Size: 60.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/4.0.2 CPython/3.11.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 277d6685407fced0230b5a06bfface4a7482ed7ff5055d78c0e3414c2465772b |
|
MD5 | b3b1f6656b3a0828a974b7cd588b39f8 |
|
BLAKE2b-256 | a1f876f41b8fa399bcdf00e7e769c6ce75d4e0282c55ffcfd27d971ff2b6bfc4 |
File details
Details for the file chasten-1.0.0-py3-none-any.whl
.
File metadata
- Download URL: chasten-1.0.0-py3-none-any.whl
- Upload date:
- Size: 58.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/4.0.2 CPython/3.11.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 921326becfb23b1cd6280ea001ffd3978a9593436b0be93373a5dea4156dceaa |
|
MD5 | 0fd3ea5f079939b0d3220967c2a1dc1b |
|
BLAKE2b-256 | 16612ef092e114fe3d726851c96334c690dcad78732ae045f7a698c26d30f353 |