Pattern Library

Grit comes with 181 out of the box patterns that can be leveraged immediately.

Migration Patterns

Migration patterns can be used to automatically migrate you to a new framework or library.

Creating a styled component inside the render method in React leads to performance issues because it dynamically generates a new component in the DOM on each render. This causes React to discard and recalculate that part of the DOM subtree every time, rather than efficiently updating only the changed parts. This can result in performance bottlenecks and unpredictable behaviour.

Convert Chai test assertions to Jest.

Converts CommonJS module.exports to ES6-style exports.

Convert Jest tests to Vitest

Converts require statements to ES6-style import.

Upgrade the Langfuse SDK to v2 following this guide.

Transform io-ts schemas to zod schema

Converts arrow function single expression to to block body

This pattern migrates from React Query v3 to React Query v4. It is the equivalent of the codemod.

Upgrade the OpenAI SDK to v4 following this guide.

Knockout.js is an older JavaScript framework that is still used by many developers. This migration helps with migrating your Knockout code to React.

The 'schemaDirectives' option in Apollo GraphQL, which was effective in ApolloServer version v2, no longer functions in versions >=3 and above. This change can have significant implications, potentially exposing authenticated endpoints, disabling rate limiting, and more, depending on the directives used. To address this, it is recommended to consult the references on creating custom directives specifically for ApolloServer versions v3 and v4.

Converts function expressions to ES6 arrow functions, including eliminating the return statement where possible.

This pattern converts React class components to functional components, with hooks.

Convert OpenAI from openai version to the v1 version, while continuing to use the global client. This is a variant of the client-based version.

Convert OpenAI from openai version to the v1 version.

Upgrade the Langfuse SDK to v2 following this guide.

This pattern upgrades code to TruLens v1.x by replacing deprecated imports and class usage.

JavaScript to TypeScript (js_to_ts)

JavaScript pattern

AngularJS to Angular*

JavaScript pattern

Angular to React*

JavaScript pattern

Linters

These patterns can autofix many common JavaScript mistakes, including issues that eslint doesn't fix automatically.

Prefer to use early returns to keep functions flat.

Harden DOM usage*

JavaScript pattern

Miscellaneous

PgTAP is a unit testing framework for Postgres. This pattern adds a unit test checking a procedure has been correctly defined.

In Postgres, function and procedure bodies need to be wrapped in $$dollar quotes$$. This pattern wraps a PLSQL CREATE PROCEDURE body in dollar quotes and adds a language specifier.

This pattern replaces Markdown links with their bare text.

Finds nested match expressions where the patterns may be combined to reduce the number of branches.

Checks for the use of format!("string literal with no argument") and format!("{}", foo) where foo is a string.

It is more idiomatic to remove the return keyword and the semicolon.

The hashing functions md2, md4, md5, and sha1 are detected as cryptographically insecure due to known vulnerabilities. It is advisable to use more secure hashing algorithms for cryptographic purposes.

str::bytes().count() is longer and may not be as performant as using str::len().

Redundant layers of nesting add undesirable complexity.

Standardize on a GitHub Actions runner.

This pattern helps with upgrading Concourse pipelines to version 7.

Grit includes standard patterns for declaratively adding, removing, and updating imports.

Convert comparisons to NaN (e.g., x == NaN) to use isNaN (e.g., isNaN(x)).

Use explicit conversions between types, e.g., '' + x => String(s).

This rule hoists the assignments out of return. Because an assignment, = is easy to confuse with a comparison, ==, The best practice is not to use any assignments in return statements.

The group_blocks function takes a target list and returns a list of lists, where each sublist is a block of items that are adjacent to each other in the original program.

JavaScript’s alert is often used while debugging code, which should be removed before deployment to production.

The Apollo GraphQL server lacks the 'csrfPrevention' option. This option is 'false' by the default in v3 of the Apollo GraphQL v3, which can enable CSRF attacks.

If a useEffect depends on layout etc. it should switch to useLayoutEffect.

If a PureComponent has the shouldComponentUpdate method, convert it to a regular Component.

The if and else statements should not be used inline. Instead, use a block statement.

This pattern replaces React default import method references (e.g. React.ReactNode) with destructured named imports (import { ReactNode } from 'react'). Running this will also make sure that React is imported.

Add any type annotation to caught errors. It is a common source of tsc errors.

serialize-javascript used with unsafe parameter, this could be vulnerable to XSS.

Creating and using a large number of zlib objects simultaneously can cause significant memory fragmentation. It is strongly recommended that the results of compression operations be cached or made synchronous to avoid duplication of effort

Converts ES6-style import to require statements.

arguments.caller and arguments.called have been deprecated.

The Promise is already executed asynchronously and exceptions thrown by the function will be lost.

Convert non-strict equality checking, using ==, to the strict version, using ===.

Remove the shouldComponentUpdate method from PureComponent. PureComponent already has an implementation.

Replaces replaceAll with replace, when it uses a regex pattern.

Replaces innerHtml with innerText, which is safer in most cases.

Use _iterator_ instead of __iterator__. __iterator__ is obsolete and is not implemented by all browsers.

Components without children can be self-closed to avoid unnecessary extra closing tag.

If a for counter moves in the wrong direction the loop will run infinitely. Mostly, an infinite for loop is a typo and causes a bug.

Utility patterns for matching literals.

Calling Symbol with the new operator throws a TypeError exception.

Prefer natural language style conditions in favour of Yoda style conditions.

Call hasOwnProperty, isPrototypeOf, propertyIsEnumerable methods only from Object.prototype.
Otherwise it can cause errors.

ES7 introduced the includes method for arrays so bitwise and comparisons to -1 are no longer needed.

The Apollo GraphQL server sets the 'csrfPrevention' option to false. This can enable CSRF attacks.

Older code often uses the function prototype to create "classes" out of functions. This upgrades those to ES6 class syntax.

The code in production should not contain a debugger. It causes the browser to stop executing the code and open the debugger.

Remove unreachable code found after return / throw / continue or break statements.

Replaces export default function () { } with export default function main () { } and export default () => { } with const main = () => { }; export default main

Remove console.log statements.

Split a tRPC router into multiple files, one per route.

This pattern removes unused imports of top level modules like import React from "react" or import * as lodash from "lodash".

Comparing to null needs a type-checking operator (=== or !==), to avoid incorrect results when the value is undefined.

Replace wildcard imports with explicit imports.

JavaScript’s prompt function is widely considered to be obtrusive as UI elements and should be replaced by a more appropriate custom UI implementation.

Calling setState on the current state is always a no-op. Did you mean to change the state like $Y(!$X) instead?

Avoid hard-coding secrets, such as credentials and sensitive data, directly into your application's source code. This practice poses a security risk as the information may be inadvertently leaked.

Disable skipping Jest tests without an explanation.

Negates key instead of the entire expression, which is likely a bug.

Find uncaught HTTP requests and wrap it with try {} catch{ }

It is a good practice to throw Error objects on exceptions because they automatically keep track of where they were created.

Migrate the Drizzle DB schema from MySQL to PostgreSQL.

Default Grit patterns are not generally aware of variable scoping, but you can use the identifier_scope pattern to find (or exclude) scopes where an identifier has been locally defined.

Migrate Link component children to Next13

The literal notation avoids the single-argument pitfall or the Array global being redefined.

If the noAssert flag is set, offset can go beyond the end of the Buffer, which is a security vulnerability.

The {} literal form is a more concise way of creating an object.

expect.arrayContaining can be used to validate an array containing multiple different elements, so multiple statements are not required.

Bitwise operators & or | are often used by mistake instead of && or ||, which can cause unexpected errors.

Some template engines allow disabling HTML escaping, which can allow XSS vulnerabilities.

The upsert pattern can be used to update a value in an object, or insert it if the key doesn't already exist.

If $condition ? $answer:$answer then this expression returns $answer. This is probably a human error.

JavaScript’s confirm function is widely considered to be obtrusive as UI elements and should be replaced by a more appropriate custom UI implementation.

ES7 introduced the exponentiation operator ** so that using Math.pow is no longer necessary.

Unusued variables should not be defined on contracts, either as state variables or as local variables. This corresponds to SWC-103.

Looking for variations of the upgradable proxy pattern.

Say we do not want mulDivRoundUp.

Detected wildcard access granted to sts:AssumeRole. This means anyone with your AWS account ID and the name of the role can assume the role. Instead, limit to a specific identity in your account, like this: arn:aws:iam::<account_id>:root.

Detected public S3 bucket. This policy allows anyone to have some kind of access to the bucket. The exact level of access and types of actions allowed will depend on the configuration of bucket policy and ACLs. Please review the bucket configuration to make sure they are set with intended values.

This pattern reverses key-value pairs when the value is a string.

An example illustrating the upgrade_dependency utility function, which upgrades a dependency to a specified semantic version in package.json, or adds it if it is not present.

Adds "strict": true, "allowJs": true, "checkJs": false from a tsconfig's compilerOptions, and then removes existing redundant options (such as noImplicitAny).

Update a module by specifying its old source and the new one.

Find a key-value pair in Terraform HCL.

Grit includes standard patterns for declaratively finding, adding, and updating imports in Python.

Identified the utilization of an insecure MD4 or MD5 hash function, both of which have well-documented vulnerabilities and are deemed deprecated. It is recommended to replace them with more secure options such as SHA256 or a comparable hash function for improved security.

If you're generating a CSV file using the built-in csv module and incorporating user data, there's a potential security risk. An attacker might inject a formula into the CSV file, which, when imported into a spreadsheet application, could execute a malicious script, leading to data theft or even malware installation on the user's computer. To enhance security, consider using defusedcsv as a direct substitute for csv. defusedcsv maintains the same API but aims to thwart formula injection attempts, providing a safer way to create CSV files.

Add thousands separator (1_000_000) to numbers (ints and floats, positive or negative).

JsonResponse in Django offers a concise and efficient way to return JSON responses compared to using json.dumps along with HttpResponse. It simplifies the process by automatically handling serialization and setting the correct content type.

We should close the file object opened without corresponding close.

Grit includes standard patterns for declaratively finding, adding, and updating imports in Python.

Replace unneeded list comprehensions with direct generators.

Replace constant collection with boolean in boolean contexts.

To get the current time in UTC use a datetime object with the timezone explicitly set to UTC.

Use the walrus operator for snippets with a match followed by an if.

Replaces 2 individual bound checks with a single combined bound check.

Replaces an assignment to the same variable done across an if-else with a ternary operator when both are equivalent.

Detected hardcoded temp directory. Consider using tempfile.TemporaryFile instead

When a boolean expression is used in an if-else to get a boolean value, use the boolean value directly.

Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for no data: NULL, and the empty string. In most cases, it's redundant to have two possible values for "no data" the Django convention is to use the empty string, not NULL.

Prefer using tempfile.NamedTemporaryFile instead. According to the official Python documentation, the tempfile.mktemp function is considered unsafe and should be avoided. This is because the generated file name may initially point to a non-existent file, and by the time you attempt to create it, another process may have already created a file with the same name, leading to potential conflicts.

Use list, set or dictionary comprehensions directly instead of calling list(), dict() or set().

flask.jsonify() simplifies returning JSON from Flask routes by automatically serializing Python objects into JSON format and setting the appropriate Content-Type header, resulting in cleaner and more readable code while ensuring consistency and compatibility with web standards.

The Mux Python SDK has been rewritten for v3 and contains significant changes.

Rewrite print statements using log.

This pattern transforms a loop that computes the product of a list of numbers into a call to math.prod (introduced in Python 3.8).

The sort($list) function sorts a list of items in ascending order, based on the lexical order of the items.

Replaces dictionaries created with for loops with dictionary comprehensions.

Grit includes standard patterns for declaratively finding, adding, and updating imports in Python.

Replaces cases where deletions are made via for loops with comprehensions.

Grit includes standard patterns for declaratively finding, adding, and updating imports in Python.

Some binary operations can be simplified into constants, this lint performs those simplifications.

Grit includes standard patterns for declaratively finding, adding, and updating imports in Python.

Airflow supports decorator syntax (@task, @dag) for defining workflows. It is recommended to use them over the legacy python classes.

We should remove debugger from production code

Disable skipping pytest tests without an explanation.

Use $FORM.cleaned_data[] instead of request.POST[] after form.is_valid() has been executed to only access sanitized data.

Converts any() functions to simpler in statements.

Be cautious when using $F.name without preceding it with .flush() or .close(), as it may result in an error. This is because the file referenced by $F.name might not exist at the time of use. To prevent issues, ensure that you either call .flush() to write any buffered data to the file or close the file with .close() before referencing $F.name.

Detected use of the 'none' algorithm in a JWT token. The 'none' algorithm assumes the integrity of the token has already been verified. This would allow a malicious actor to forge a JWT token that will automatically be verified. Do not explicitly use the 'none' algorithm. Instead, use an algorithm such as 'HS256'.

Creating a new Throwable without actually throwing or binding it is useless and is probably due to a mistake.

This pattern uses static analysis to find private methods that are only used once, then uses AI to inline them.

Because of floating point imprecision, the BigDecimal(double) constructor can be somewhat unpredictable. It is better to use BigDecimal.valueOf(double).

Unused private methods, excepting methods with annotations and special methods overriding Java's default behaviour, constitute dead code and should therefore be removed.

Assignment inside a condition like this $x = false is usually accidental, this is likely meant to be a comparison $x == false.

Simplify redundant self-comparison ($var == $var) to achieve clearer code logic and avoid unnecessary repetition.

Assignment inside a condition is usually accidental, this is likely meant to be a comparison.

It is redundant and usually a bug when a variable is assigned to itself.

JUnit silently ignores private classes and private methods, static methods, and methods returning a value without being a TestFactory.

Unused private fields constitute dead code and should therefore be removed.

Grit includes standard patterns for declaratively adding or finding imports.

$VALUE serves as a loop pointer that might be exported from the loop. Since this pointer is shared across loop iterations, the exported reference will consistently point to the last loop value, potentially leading to unintended consequences. To address this issue, duplicate the pointer within the loop to ensure each iteration has its own distinct reference.

v2.x of the Go SDK is a ground-up rewrite, using code generation from the OpenAPI spec. There are significant breaking changes.

The Go SDK has been rewritten for v5 and contains significant changes.

Using the none algorithm in a JWT token is risky because it assumes the token's integrity is already ensured. This could let a malicious actor create a fake JWT token that gets automatically verified. Avoid using none and go for a safer algorithm like HS256 instead.

Detected a channel guarded with a mutex. Channels already have an internal mutex, so this is unnecessary. Remove the mutex.

If statements that always evaluate to true or false are redundant and should be removed.

Identified a potential risk in converting the outcome of a strconv.Atoi command to int16. This may lead to integer overflow, possibly causing unforeseen issues and even privilege escalation. It is recommended to utilize strconv.ParseInt instead.

Function invocations are expected to synchronous, and this function will execute asynchronously because all it does is call a goroutine. Instead, remove the internal goroutine and call the function using go.

Identical statements found in both the if and else bodies of an if-statement. This results in the same code execution regardless of the if-expression outcome. To optimize, eliminate the if statement entirely.

Utilize filepath.Join(...) instead of path.Join(...) as it accommodates OS-specific path separators, mitigating potential issues on systems like Windows that may employ different delimiters.

* Patterns with an asterisk are in private alpha with select customers.