Moderne Recipes
This doc includes every recipe that is exclusive to users of Moderne. For a full list of all recipes, check out our recipe catalog. For more information about how to use Moderne for automating code refactoring and analysis at scale, contact us.
io.moderne.recipe
recipes-code-quality
- OpenRewrite.CSharp.Recipes.AddNuGetPackageReference
- Add NuGet package reference
- Adds a
<PackageReference>element to .csproj files if not already present.
- OpenRewrite.CSharp.Recipes.ChangeDotNetTargetFramework
- Change .NET target framework
- Changes the
<TargetFramework>or<TargetFrameworks>value in .csproj files. For multi-TFM projects, replaces the matching framework within the semicolon-delimited list.
- OpenRewrite.CSharp.Recipes.FindNuGetPackageReference
- Find NuGet package reference
- Searches for .csproj files that reference a specific NuGet package. Intended for use as a precondition to scope other recipes.
- OpenRewrite.CSharp.Recipes.RemoveNuGetPackageReference
- Remove NuGet package reference
- Removes a
<PackageReference>element from .csproj files.
- OpenRewrite.CSharp.Recipes.UpgradeNuGetPackageVersion
- Upgrade NuGet package version
- Upgrades the version of a NuGet
<PackageReference>or<PackageVersion>in .csproj and Directory.Packages.props files. Handles property references by updating the property value instead of the version attribute. Uses NuGet.Versioning for correct version semantics.
- OpenRewrite.Recipes.CodeQuality.CodeQuality
- Code quality
- All C# code quality recipes, organized by category.
- OpenRewrite.Recipes.CodeQuality.Formatting.AddNewLineAfterOpeningBrace
- Add newline after opening brace
- Add newline after opening brace so the first statement starts on its own line.
- OpenRewrite.Recipes.CodeQuality.Formatting.AddNewLineBeforeReturn
- Add newline before return
- Add a blank line before return statements that follow other statements.
- OpenRewrite.Recipes.CodeQuality.Formatting.AddParagraphToDocComment
- Add paragraph to documentation comment
- Format multi-line documentation comments with paragraph elements.
- OpenRewrite.Recipes.CodeQuality.Formatting.AddParameterToDocComment
- Add parameter name to documentation comment
- Add missing param elements to XML documentation comments.
- OpenRewrite.Recipes.CodeQuality.Formatting.AddSummaryElementToDocComment
- Add summary to documentation comment
- Add summary text to documentation comments with empty summary elements.
- OpenRewrite.Recipes.CodeQuality.Formatting.AddSummaryToDocComment
- Add summary element to documentation comment
- Add missing summary element to XML documentation comments.
- OpenRewrite.Recipes.CodeQuality.Formatting.AddTypeParamToDocComment
- Add 'typeparam' element to documentation comment
- Add missing 'typeparam' elements to XML documentation comments.
- OpenRewrite.Recipes.CodeQuality.Formatting.FixDocCommentTag
- Fix documentation comment tag
- Replace inline <code> elements with <c> elements in XML documentation comments.
- OpenRewrite.Recipes.CodeQuality.Formatting.FormatAccessorList
- Format accessor list
- Format property accessor list for consistent whitespace.
- OpenRewrite.Recipes.CodeQuality.Formatting.FormatDocumentationSummary
- Format documentation summary
- Format XML documentation summary on a single line or multiple lines.
- OpenRewrite.Recipes.CodeQuality.Formatting.FormatSwitchSection
- Format switch section
- Ensure consistent formatting of switch sections.
- OpenRewrite.Recipes.CodeQuality.Formatting.FormattingCodeQuality
- Formatting code quality
- Code formatting recipes for C#.
- OpenRewrite.Recipes.CodeQuality.Formatting.InvalidDocCommentReference
- Invalid reference in a documentation comment
- Find invalid cref or paramref references in XML documentation comments.
- OpenRewrite.Recipes.CodeQuality.Formatting.NormalizeWhitespace
- Normalize whitespace
- Normalize whitespace for consistent formatting.
- OpenRewrite.Recipes.CodeQuality.Formatting.OrderDocCommentElements
- Order elements in documentation comment
- Order param/typeparam elements to match declaration order.
- OpenRewrite.Recipes.CodeQuality.Linq.CombineLinqMethods
- Combine LINQ methods
- Combine
.Where(predicate).First()and similar patterns into.First(predicate), and consecutive.Where().Where()calls into a single.Where()with a combined predicate. Eliminating intermediate LINQ calls improves readability.
- OpenRewrite.Recipes.CodeQuality.Linq.FindOptimizeCountUsage
- Find Count() comparison that could be optimized
- Detect
Count(pred) == nandCount() > ncomparisons which could useWhere().Take(n+1).Count()orSkip(n).Any()for better performance.
- OpenRewrite.Recipes.CodeQuality.Linq.FindWhereBeforeOrderBy
- Use Where before OrderBy
- Place
.Where()before.OrderBy()to filter elements before sorting. This reduces the number of items that need to be sorted.
- OpenRewrite.Recipes.CodeQuality.Linq.LinqCodeQuality
- LINQ code quality
- Optimize LINQ method calls for better readability and performance.
- OpenRewrite.Recipes.CodeQuality.Linq.OptimizeLinqSelectAverage
- Optimize LINQ Select().Average()
- Replace
items.Select(selector).Average()withitems.Average(selector).
- OpenRewrite.Recipes.CodeQuality.Linq.OptimizeLinqSelectMax
- Optimize LINQ Select().Max()
- Replace
items.Select(selector).Max()withitems.Max(selector). Passing the selector directly toMaxavoids an intermediate iterator.
- OpenRewrite.Recipes.CodeQuality.Linq.OptimizeLinqSelectMin
- Optimize LINQ Select().Min()
- Replace
items.Select(selector).Min()withitems.Min(selector). Passing the selector directly toMinavoids an intermediate iterator.
- OpenRewrite.Recipes.CodeQuality.Linq.OptimizeLinqSelectSum
- Optimize LINQ Select().Sum()
- Replace
items.Select(selector).Sum()withitems.Sum(selector).
- OpenRewrite.Recipes.CodeQuality.Linq.OptimizeLinqWhereAny
- Optimize LINQ Where().Any()
- Replace
items.Where(predicate).Any()withitems.Any(predicate). Passing the predicate directly toAnyavoids an intermediate iterator.
- OpenRewrite.Recipes.CodeQuality.Linq.OptimizeLinqWhereCount
- Optimize LINQ Where().Count()
- Replace
items.Where(predicate).Count()withitems.Count(predicate). Passing the predicate directly toCountavoids an intermediate iterator.
- OpenRewrite.Recipes.CodeQuality.Linq.OptimizeLinqWhereCountLong
- Optimize LINQ Where().LongCount()
- Replace
.Where(predicate).LongCount()with.LongCount(predicate).
- OpenRewrite.Recipes.CodeQuality.Linq.OptimizeLinqWhereFirst
- Optimize LINQ Where().First()
- Replace
items.Where(predicate).First()withitems.First(predicate).
- OpenRewrite.Recipes.CodeQuality.Linq.OptimizeLinqWhereFirstOrDefault
- Optimize LINQ Where().FirstOrDefault()
- Replace
items.Where(predicate).FirstOrDefault()withitems.FirstOrDefault(predicate).
- OpenRewrite.Recipes.CodeQuality.Linq.OptimizeLinqWhereLast
- Optimize LINQ Where().Last()
- Replace
items.Where(predicate).Last()withitems.Last(predicate).
- OpenRewrite.Recipes.CodeQuality.Linq.OptimizeLinqWhereLastOrDefault
- Optimize LINQ Where().LastOrDefault()
- Replace
.Where(predicate).LastOrDefault()with.LastOrDefault(predicate).
- OpenRewrite.Recipes.CodeQuality.Linq.OptimizeLinqWhereSingle
- Optimize LINQ Where().Single()
- Replace
items.Where(predicate).Single()withitems.Single(predicate).
- OpenRewrite.Recipes.CodeQuality.Linq.OptimizeLinqWhereSingleOrDefault
- Optimize LINQ Where().SingleOrDefault()
- Replace
items.Where(predicate).SingleOrDefault()withitems.SingleOrDefault(predicate).
- OpenRewrite.Recipes.CodeQuality.Linq.RemoveUselessOrderBy
- Remove useless OrderBy call
- Replace
.OrderBy(a).OrderBy(b)with.OrderBy(b). A secondOrderBycompletely replaces the first sort, making the first call useless.
- OpenRewrite.Recipes.CodeQuality.Linq.UseAnyInsteadOfCount
- Use Any() instead of Count() > 0
- Replace
.Count() > 0with.Any().Any()short-circuits after the first match, whileCount()enumerates all elements.
- OpenRewrite.Recipes.CodeQuality.Linq.UseCastInsteadOfSelect
- Use Cast<T>() instead of Select with cast
- Replace
.Select(x => (T)x)with.Cast<T>(). TheCast<T>()method is more concise and clearly expresses the intent.
- OpenRewrite.Recipes.CodeQuality.Linq.UseOrderByDescendingThenByDescending
- Use OrderByDescending().ThenByDescending()
- Replace
.OrderByDescending(a).OrderByDescending(b)with.OrderByDescending(a).ThenByDescending(b).
- OpenRewrite.Recipes.CodeQuality.Linq.UseOrderByThenBy
- Use ThenBy instead of second OrderBy
- Replace
items.OrderBy(a).OrderBy(b)withitems.OrderBy(a).ThenBy(b). A secondOrderBydiscards the first sort;ThenBypreserves it as a secondary key.
- OpenRewrite.Recipes.CodeQuality.Linq.UseOrderByThenByDescending
- Use OrderBy().ThenByDescending()
- Replace
.OrderBy(a).OrderByDescending(b)with.OrderBy(a).ThenByDescending(b).
- OpenRewrite.Recipes.CodeQuality.Linq.UseOrderInsteadOfOrderBy
- Use Order() instead of OrderBy() with identity
- Replace
.OrderBy(x => x)with.Order(). TheOrder()method (available since .NET 7) is a cleaner way to sort elements in their natural order.
- OpenRewrite.Recipes.CodeQuality.Naming.AsyncMethodNameShouldEndWithAsync
- Async method name should end with Async
- Rename async methods to end with 'Async' suffix.
- OpenRewrite.Recipes.CodeQuality.Naming.FindAttributeNameShouldEndWithAttribute
- Attribute name should end with 'Attribute'
- Classes that inherit from
System.Attributeshould have names ending with 'Attribute' by convention.
- OpenRewrite.Recipes.CodeQuality.Naming.FindEventArgsNameConvention
- EventArgs name should end with 'EventArgs'
- Classes that inherit from
System.EventArgsshould have names ending with 'EventArgs' by convention.
- OpenRewrite.Recipes.CodeQuality.Naming.FindExceptionNameShouldEndWithException
- Exception name should end with 'Exception'
- Classes that inherit from
System.Exceptionshould have names ending with 'Exception' by convention.
- OpenRewrite.Recipes.CodeQuality.Naming.FindFixTodoComment
- Find TODO/HACK/FIXME comments
- Detect TODO, HACK, UNDONE, and FIXME comments that indicate unfinished work.
- OpenRewrite.Recipes.CodeQuality.Naming.NamingCodeQuality
- Naming code quality
- Naming convention recipes for C# code.
- OpenRewrite.Recipes.CodeQuality.Naming.NonAsyncMethodNameShouldNotEndWithAsync
- Non-async method should not end with Async
- Remove 'Async' suffix from non-async methods.
- OpenRewrite.Recipes.CodeQuality.Naming.ParameterNameMatchesBase
- Parameter name should match base definition
- Ensure parameter names match the names used in base class or interface.
- OpenRewrite.Recipes.CodeQuality.Naming.RenameParameterAccordingToConvention
- Rename parameter to camelCase
- Detect parameters not following camelCase naming convention.
- OpenRewrite.Recipes.CodeQuality.Naming.RenamePrivateFieldAccordingToConvention
- Rename private field according to _camelCase convention
- Detect private fields not following _camelCase naming convention.
- OpenRewrite.Recipes.CodeQuality.Naming.UseNameofOperator
- Use nameof operator
- Use nameof(parameter) instead of string literal for argument exception constructors.
- OpenRewrite.Recipes.CodeQuality.Performance.AvoidBoxingOfValueType
- Avoid boxing of value type
- Avoid boxing of value type by using generic overloads or ToString().
- OpenRewrite.Recipes.CodeQuality.Performance.AvoidLockingOnPubliclyAccessible
- Avoid locking on publicly accessible instance
- Avoid lock(this), lock(typeof(T)), or lock on string literals which can cause deadlocks.
- OpenRewrite.Recipes.CodeQuality.Performance.AvoidNullReferenceException
- Avoid NullReferenceException
- Flag patterns that may throw NullReferenceException, such as using 'as' cast result without null check.
- OpenRewrite.Recipes.CodeQuality.Performance.BitOperationOnEnumWithoutFlags
- Bitwise operation on enum without Flags attribute
- Flag bitwise operations on enums that lack the Flags attribute.
- OpenRewrite.Recipes.CodeQuality.Performance.ConvertHasFlagToBitwiseOperation
- Convert HasFlag to bitwise operation
- Replace flags.HasFlag(value) with (flags & value) != 0.
- OpenRewrite.Recipes.CodeQuality.Performance.DoNotPassNonReadOnlyStructByReadOnlyRef
- Do not pass non-read-only struct by read-only reference
- Remove 'in' modifier from parameters of non-readonly struct type to avoid defensive copies.
- OpenRewrite.Recipes.CodeQuality.Performance.FindAsyncVoid
- Do not use async void
- Async void methods cannot be awaited and exceptions cannot be caught. Use
async Taskinstead, except for event handlers.
- OpenRewrite.Recipes.CodeQuality.Performance.FindAvoidClosureByUsingFactoryArg
- Find closure in GetOrAdd that could use factory argument
- Detect
ConcurrentDictionary.GetOrAddcalls with lambdas that capture variables. Use the overload with a factory argument parameter to avoid allocation.
- OpenRewrite.Recipes.CodeQuality.Performance.FindAvoidClosureInConcurrentDictionary
- Avoid closure when using ConcurrentDictionary
- ConcurrentDictionary methods like
GetOrAddmay evaluate the factory even when the key exists. Use the overload with a factory argument to avoid closure allocation.
- OpenRewrite.Recipes.CodeQuality.Performance.FindAvoidClosureInMethod
- Find closure in GetOrAdd/AddOrUpdate factory
- Detect closures in lambdas passed to
GetOrAddorAddOrUpdate. Use the factory overload that accepts a state argument to avoid allocations.
- OpenRewrite.Recipes.CodeQuality.Performance.FindBlockingCallsInAsync
- Find blocking calls in async methods
- Detect
.Wait(),.Result, and.GetAwaiter().GetResult()calls in async methods. Blocking calls in async methods can cause deadlocks.
- OpenRewrite.Recipes.CodeQuality.Performance.FindDoNotUseBlockingCall
- Do not use blocking calls on tasks
- Avoid
.Wait(),.Result, and.GetAwaiter().GetResult()on tasks. These can cause deadlocks. Useawaitinstead.
- OpenRewrite.Recipes.CodeQuality.Performance.FindDoNotUseToStringIfObject
- Do not use ToString on GetType result
- Using
.GetType().ToString()returns the full type name. Consider using.GetType().Nameor.GetType().FullNameinstead for clarity.
- OpenRewrite.Recipes.CodeQuality.Performance.FindEqualityComparerDefaultOfString
- Find EqualityComparer<string>.Default usage
- Detect
EqualityComparer<string>.Defaultwhich uses ordinal comparison. Consider using an explicitStringComparerinstead.
- OpenRewrite.Recipes.CodeQuality.Performance.FindGetTypeOnSystemType
- Find GetType() called on System.Type
- Detect
typeof(T).GetType()which returnsSystem.RuntimeTypeinstead of the expectedSystem.Type. Usetypeof(T)directly.
- OpenRewrite.Recipes.CodeQuality.Performance.FindImplicitCultureSensitiveMethods
- Find implicit culture-sensitive string methods
- Detect calls to
ToLower()andToUpper()without culture parameters. These methods use the current thread culture, which may cause unexpected behavior.
- OpenRewrite.Recipes.CodeQuality.Performance.FindImplicitCultureSensitiveToString
- Find implicit culture-sensitive ToString calls
- Detect
.ToString()calls without format arguments. On numeric and DateTime types, these use the current thread culture.
- OpenRewrite.Recipes.CodeQuality.Performance.FindLinqOnDirectMethods
- Find LINQ methods replaceable with direct methods
- Detect LINQ methods like
.Count()that could be replaced with direct collection properties. Direct access avoids enumeration overhead.
- OpenRewrite.Recipes.CodeQuality.Performance.FindMakeMethodStatic
- Find methods that could be static
- Detect private methods that don't appear to use instance members and could be marked
staticfor clarity and performance.
- OpenRewrite.Recipes.CodeQuality.Performance.FindMissingCancellationToken
- Find methods not forwarding CancellationToken
- Detect calls to async methods that may have CancellationToken overloads but are called without one. Uses name-based heuristics.
- OpenRewrite.Recipes.CodeQuality.Performance.FindMissingStructLayout
- Find structs without StructLayout attribute
- Detect struct declarations without
[StructLayout]attribute. Adding[StructLayout(LayoutKind.Auto)]allows the CLR to optimize field layout for better memory usage.
- OpenRewrite.Recipes.CodeQuality.Performance.FindMissingTimeoutForRegex
- Add timeout to Regex
- Regex without a timeout can be vulnerable to ReDoS attacks. Specify a
TimeSpantimeout or useRegexOptions.NonBacktracking.
- OpenRewrite.Recipes.CodeQuality.Performance.FindMissingWithCancellation
- Find missing WithCancellation on async enumerables
- Detect async enumerable iteration without
.WithCancellation(). Async enumerables should forward CancellationToken via WithCancellation.
- OpenRewrite.Recipes.CodeQuality.Performance.FindNaNComparison
- Do not use NaN in comparisons
- Comparing with
NaNusing==always returns false. Usedouble.IsNaN(x)instead.
- OpenRewrite.Recipes.CodeQuality.Performance.FindOptimizeEnumerableCountVsAny
- Find LINQ Count() on materialized collection
- Detect LINQ
Count()orAny()on types that have aCountorLengthproperty. Use the property directly for O(1) performance.
- OpenRewrite.Recipes.CodeQuality.Performance.FindOptimizeGuidCreation
- Find Guid.Parse with constant string
- Detect
Guid.Parse("...")with constant strings. Consider usingnew Guid("...")or a static readonly field for better performance.
- OpenRewrite.Recipes.CodeQuality.Performance.FindOptimizeStartsWith
- Use char overload for single-character string methods
- Convert string methods with single-character string literals to use char overloads for better performance.
- OpenRewrite.Recipes.CodeQuality.Performance.FindSequenceEqualForSpan
- Find Span<char> equality that should use SequenceEqual
- Detect
==and!=operators onSpan<char>orReadOnlySpan<char>which compare references. UseSequenceEqualfor content comparison.
- OpenRewrite.Recipes.CodeQuality.Performance.FindSimplifyStringCreate
- Find simplifiable string.Create calls
- Detect
string.Create(CultureInfo.InvariantCulture, ...)calls that could be simplified to string interpolation when all parameters are culture-invariant.
- OpenRewrite.Recipes.CodeQuality.Performance.FindStreamReadResultNotUsed
- Find unused Stream.Read return value
- Detect calls to
Stream.ReadorStream.ReadAsyncwhere the return value is discarded. The return value indicates how many bytes were actually read.
- OpenRewrite.Recipes.CodeQuality.Performance.FindStringCreateInsteadOfFormattable
- Find FormattableString that could use string.Create
- Detect
FormattableStringusage wherestring.Createwith anIFormatProvidercould be used for better performance.
- OpenRewrite.Recipes.CodeQuality.Performance.FindStringFormatShouldBeConstant
- String.Format format string should be constant
- The format string passed to
string.Formatshould be a compile-time constant to enable analysis and avoid runtime format errors.
- OpenRewrite.Recipes.CodeQuality.Performance.FindStringGetHashCode
- Find string.GetHashCode() without StringComparer
- Detect calls to
string.GetHashCode()without aStringComparer. The defaultGetHashCode()may produce different results across platforms.
- OpenRewrite.Recipes.CodeQuality.Performance.FindStructWithDefaultEqualsAsKey
- Find Dictionary/HashSet with struct key type
- Detect
DictionaryorHashSetusage with struct types as keys. Structs without overriddenEquals/GetHashCodeuse slow reflection-based comparison.
- OpenRewrite.Recipes.CodeQuality.Performance.FindUseAttributeIsDefined
- Find GetCustomAttributes that could use Attribute.IsDefined
- Detect
GetCustomAttributes().Any()or similar patterns whereAttribute.IsDefinedwould be more efficient.
- OpenRewrite.Recipes.CodeQuality.Performance.FindUseContainsKeyInsteadOfTryGetValue
- Use ContainsKey instead of TryGetValue with discard
- When only checking if a key exists, use
ContainsKeyinstead ofTryGetValuewith a discarded out parameter.
- OpenRewrite.Recipes.CodeQuality.Performance.FindUseExplicitCaptureRegexOption
- Use RegexOptions.ExplicitCapture
- Use
RegexOptions.ExplicitCaptureto avoid capturing unnamed groups, which improves performance.
- OpenRewrite.Recipes.CodeQuality.Performance.FindUseIndexerInsteadOfLinq
- Find LINQ methods replaceable with indexer
- Detect LINQ methods like
.First()and.Last()that could be replaced with direct indexer access for better performance.
- OpenRewrite.Recipes.CodeQuality.Performance.FindUseRegexSourceGenerator
- Find Regex that could use source generator
- Detect
new Regex(...)calls that could benefit from the[GeneratedRegex]source generator attribute for better performance (.NET 7+).
- OpenRewrite.Recipes.CodeQuality.Performance.FindUseTimeProviderOverload
- Find calls that could use TimeProvider
- Detect
DateTime.UtcNow,DateTimeOffset.UtcNow, andTask.Delaycalls that could use aTimeProviderparameter for better testability (.NET 8+).
- OpenRewrite.Recipes.CodeQuality.Performance.FindUseValuesContainsInsteadOfValues
- Find Values.Contains() instead of ContainsValue()
- Detect
.Values.Contains(value)on dictionaries. Use.ContainsValue(value)instead.
- OpenRewrite.Recipes.CodeQuality.Performance.MakeParameterRefReadOnly
- Make parameter ref read-only
- Use in parameter modifier for large struct parameters.
- OpenRewrite.Recipes.CodeQuality.Performance.OptimizeMethodCall
- Optimize method call
- Replace inefficient method calls with more optimal equivalents.
- OpenRewrite.Recipes.CodeQuality.Performance.OptimizeStringBuilderAppend
- Optimize StringBuilder.Append usage
- Optimize StringBuilder method calls: use char overloads for single-character strings, remove redundant ToString() calls, replace string.Format with AppendFormat, and split string concatenation into chained Append calls.
- OpenRewrite.Recipes.CodeQuality.Performance.PerformanceCodeQuality
- Performance code quality
- Performance optimization recipes for C# code.
- OpenRewrite.Recipes.CodeQuality.Performance.ReplaceEnumToStringWithNameof
- Replace Enum.ToString() with nameof
- Replace
MyEnum.Value.ToString()withnameof(MyEnum.Value). Thenameofoperator is evaluated at compile time, avoiding runtime reflection.
- OpenRewrite.Recipes.CodeQuality.Performance.ReturnCompletedTask
- Return completed task instead of null
- Replace return null in Task-returning methods with return Task.CompletedTask.
- OpenRewrite.Recipes.CodeQuality.Performance.ThrowingNotImplementedException
- Throwing of new NotImplementedException
- Find code that throws new NotImplementedException, which may indicate unfinished implementation.
- OpenRewrite.Recipes.CodeQuality.Performance.UnnecessaryExplicitEnumerator
- Remove unnecessary explicit enumerator
- Use foreach instead of explicit enumerator pattern.
- OpenRewrite.Recipes.CodeQuality.Performance.UseArrayEmpty
- Use Array.Empty<T>() instead of new T[0]
- Use Array.Empty<T>() instead of allocating empty arrays.
- OpenRewrite.Recipes.CodeQuality.Performance.UseContainsKey
- Use ContainsKey instead of Keys.Contains
- Replace
.Keys.Contains(key)with.ContainsKey(key)on dictionaries for O(1) performance.
- OpenRewrite.Recipes.CodeQuality.Performance.UseCountProperty
- Use Count/Length property instead of Count()
- Replace collection.Count() with collection.Count when available.
- OpenRewrite.Recipes.CodeQuality.Performance.UseRegexIsMatch
- Use Regex.IsMatch
- Replace Regex.Match(s, p).Success with Regex.IsMatch(s, p).
- OpenRewrite.Recipes.CodeQuality.Performance.UseStringBuilderAppendLine
- Use StringBuilder.AppendLine
- Replace
sb.Append("\n")withsb.AppendLine().
- OpenRewrite.Recipes.CodeQuality.Performance.UseStringComparison
- Use StringComparison
- Replace case-insensitive string comparisons using
ToLower()/ToUpper()with overloads that acceptStringComparison.OrdinalIgnoreCase.
- OpenRewrite.Recipes.CodeQuality.Performance.UseStringConcatInsteadOfJoin
- Use string.Concat instead of string.Join
- Replace
string.Join("", args)withstring.Concat(args).
- OpenRewrite.Recipes.CodeQuality.Redundancy.FileContainsNoCode
- File contains no code
- Find files that contain no code, only using directives, comments, or whitespace.
- OpenRewrite.Recipes.CodeQuality.Redundancy.FindUnusedInternalType
- Find internal types that may be unused
- Detect
internal(non-public) classes that may be unused. Review these types and remove them if they are no longer needed.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RedundancyCodeQuality
- Redundancy code quality
- Remove redundant code from C# sources.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveArgumentListFromAttribute
- Remove argument list from attribute
- Remove empty argument list from attribute.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveBracesFromRecordDeclaration
- Remove braces from record declaration
- Remove unnecessary braces from record declarations with no body.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveEmptyCatchClause
- Remove empty catch clause
- Remove empty catch clauses that silently swallow exceptions without any logging or handling.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveEmptyDestructor
- Remove empty destructor
- Remove destructors (finalizers) with empty bodies.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveEmptyFinallyClause
- Remove empty finally clause
- Remove
finally \{ \}clauses that contain no statements. An empty finally block serves no purpose.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveEmptyForBody
- Flag empty for loop body
- Flag
forloops with empty bodies as potential dead code.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveEmptyForEachBody
- Remove empty foreach body
- Remove
foreachloops with empty bodies, which iterate without effect.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveEmptySyntax
- Remove empty syntax
- Remove empty namespace, class, struct, interface, and enum declarations.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveEmptyWhileBody
- Remove empty while body
- Remove
while (cond) \{ \}loops with empty bodies as they serve no purpose.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveEnumDefaultUnderlyingType
- Remove enum default underlying type
- Remove : int from enum declaration since int is the default.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveExplicitClassFromRecord
- Remove explicit 'class' from record
- Remove the redundant
classkeyword fromrecord classdeclarations. Records are reference types by default.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemovePartialModifierFromSinglePart
- Remove partial modifier from single-part type
- Remove
partialmodifier from types that have only one part.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantAsOperator
- Remove redundant as operator
- Remove redundant 'as' operator when the expression already has the target type.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantAssignment
- Remove redundant assignment
- Remove assignments where the value is immediately returned.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantAsyncAwait
- Remove redundant async/await
- Remove redundant async/await when a Task can be returned directly.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantAutoPropertyInit
- Remove redundant constructor
- Remove empty parameterless constructors that duplicate the implicit default.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantAutoPropertyInitialization
- Remove redundant auto-property initialization
- Remove auto-property initializers that assign the default value.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantBaseConstructorCall
- Remove redundant base constructor call
- Remove
: base()parameterless base constructor call since it's implicit.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantBaseInterface
- Remove redundant base interface
- Remove interface that is already inherited by another implemented interface.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantCast
- Remove redundant cast
- Remove unnecessary casts when the expression already has the target type.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantCatchBlock
- Remove redundant catch block
- Remove try-catch blocks where every catch clause only rethrows the exception.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantComma
- Remove redundant comma
- Remove redundant trailing comma in enum declarations.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantDefaultFieldInitialization
- Remove redundant default field initialization
- Remove field initializations that assign the default value (e.g.,
int x = 0,bool b = false,string s = null,object o = default).
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantDefaultSwitchSection
- Remove redundant default switch section
- Remove default switch section that only contains break.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantDelegateCreation
- Remove redundant delegate creation
- Remove unnecessary
new EventHandler(M)whenMcan be used directly.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantDisposeOrClose
- Remove redundant Dispose/Close call
- Remove Dispose/Close calls on objects already in a using block.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantOverridingMember
- Remove redundant overriding member
- Remove overriding member that only calls the base implementation.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantParentheses
- Remove redundant parentheses
- Remove unnecessary parentheses around expressions in return statements and assignments.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantRegion
- Remove redundant region
- Remove #region/#endregion directives.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantSealedModifier
- Remove redundant sealed modifier
- Remove
sealedmodifier on members of sealed classes, since it's redundant.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantSealedModifierFromOverride
- Remove redundant 'sealed' modifier from override
- Remove redundant 'sealed' modifier from an overriding member in a sealed class.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantStatement
- Remove redundant statement
- Remove redundant
return;at end of void method orcontinue;at end of loop body.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantStringToCharArrayCall
- Remove redundant ToCharArray() call
- Remove
ToCharArray()calls in foreach loops where iterating over the string directly produces the same result.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveRedundantToStringCall
- Remove redundant ToString() call
- Remove
ToString()calls on expressions that are already strings.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveUnnecessaryCaseLabel
- Remove unnecessary case label
- Remove case labels from switch section that has default label.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveUnnecessaryElse
- Remove unnecessary else clause
- Remove
elseclause when theifbody always terminates withreturn,throw,break,continue, orgoto.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveUnnecessarySemicolon
- Remove unnecessary semicolon at end of declaration
- Remove unnecessary semicolon at the end of a declaration.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveUnusedDocCommentElement
- Unused element in documentation comment
- Remove unused param/typeparam elements from XML documentation.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveUnusedMemberDeclaration
- Remove unused member declaration
- Remove member declarations that are never referenced.
- OpenRewrite.Recipes.CodeQuality.Redundancy.RemoveUnusedThisParameter
- Unused 'this' parameter
- Remove unused 'this' parameter from extension methods.
- OpenRewrite.Recipes.CodeQuality.Redundancy.ResourceCanBeDisposedAsynchronously
- Resource can be disposed asynchronously
- Use
await usinginstead ofusingwhen the resource implements IAsyncDisposable.
- OpenRewrite.Recipes.CodeQuality.Redundancy.UnnecessaryEnumFlag
- Unnecessary enum flag
- Remove unnecessary enum flag value that is a combination of other flags.
- OpenRewrite.Recipes.CodeQuality.Redundancy.UnnecessaryInterpolatedString
- Remove unnecessary interpolated string
- Replace interpolated strings with no interpolations with regular strings.
- OpenRewrite.Recipes.CodeQuality.Redundancy.UnnecessaryInterpolation
- Unnecessary interpolation
- Remove unnecessary string interpolation, for example simplifying
$"\{x\}"tox.ToString().
- OpenRewrite.Recipes.CodeQuality.Redundancy.UnnecessaryNullCheck
- Remove unnecessary null check
- Remove null check that is unnecessary because the value is known to be non-null.
- OpenRewrite.Recipes.CodeQuality.Redundancy.UnnecessaryNullForgivingOperator
- Remove unnecessary null-forgiving operator
- Remove ! operator where expression is already non-nullable.
- OpenRewrite.Recipes.CodeQuality.Redundancy.UnnecessaryRawStringLiteral
- Remove unnecessary raw string literal
- Convert raw string literal to regular string when not needed.
- OpenRewrite.Recipes.CodeQuality.Redundancy.UnnecessaryUnsafeContext
- Remove unnecessary unsafe context
- Remove unsafe blocks that do not contain unsafe code.
- OpenRewrite.Recipes.CodeQuality.Redundancy.UnnecessaryVerbatimStringLiteral
- Remove unnecessary verbatim string literal
- Remove @ prefix from string literals that do not contain escape sequences.
- OpenRewrite.Recipes.CodeQuality.Redundancy.UseRethrow
- Use rethrow instead of throw ex
- Replace
throw ex;withthrow;inside catch clauses whenexis the caught exception variable. A barethrowpreserves the original stack trace.
- OpenRewrite.Recipes.CodeQuality.Simplification.CombineWhereMethodChain
- Combine 'Enumerable.Where' method chain
- Combine consecutive Enumerable.Where method calls into a single call with a combined predicate.
- OpenRewrite.Recipes.CodeQuality.Simplification.ConvertAnonymousMethodToLambda
- Convert anonymous method to lambda
- Convert anonymous method delegate syntax to lambda expression.
- OpenRewrite.Recipes.CodeQuality.Simplification.ConvertIfToAssignment
- Convert 'if' to assignment
- Convert 'if' statement that assigns boolean literals to a simple assignment with the condition expression.
- OpenRewrite.Recipes.CodeQuality.Simplification.ConvertInterpolatedStringToConcatenation
- Convert interpolated string to concatenation
- Detect string interpolations that could be simplified to concatenation.
- OpenRewrite.Recipes.CodeQuality.Simplification.ExpressionAlwaysTrueOrFalse
- Expression is always true or false
- Simplify
x == xtotrueandx != xtofalse.
- OpenRewrite.Recipes.CodeQuality.Simplification.InlineLazyInitialization
- Inline lazy initialization
- Use null-coalescing assignment (??=) for lazy initialization.
- OpenRewrite.Recipes.CodeQuality.Simplification.InlineLocalVariable
- Inline local variable
- Inline local variable that is assigned once and used once immediately.
- OpenRewrite.Recipes.CodeQuality.Simplification.JoinStringExpressions
- Join string expressions
- Join consecutive string literal concatenations into a single literal.
- OpenRewrite.Recipes.CodeQuality.Simplification.MergeElseWithNestedIf
- Merge else with nested if
- Merge
else \{ if (...) \{ \} \}intoelse if (...) \{ \}when the else block contains only a single if statement.
- OpenRewrite.Recipes.CodeQuality.Simplification.MergeIfWithParentIf
- Merge if with parent if
- Merge
if (a) \{ if (b) \{ ... \} \}intoif (a && b) \{ ... \}when the outer if body contains only a single nested if without else.
- OpenRewrite.Recipes.CodeQuality.Simplification.MergeSwitchSections
- Merge switch sections with equivalent content
- Merge switch case labels that have identical bodies.
- OpenRewrite.Recipes.CodeQuality.Simplification.RemoveRedundantBooleanLiteral
- Remove redundant boolean literal
- Remove redundant
== truecomparison from boolean expressions.
- OpenRewrite.Recipes.CodeQuality.Simplification.RemoveUnnecessaryBraces
- Remove unnecessary braces
- Remove braces from single-statement blocks where they are optional.
- OpenRewrite.Recipes.CodeQuality.Simplification.SimplificationCodeQuality
- Simplification code quality
- Simplify expressions and patterns in C# code.
- OpenRewrite.Recipes.CodeQuality.Simplification.SimplifyArgumentNullCheck
- Simplify argument null check
- Use ArgumentNullException.ThrowIfNull(arg) instead of manual null check.
- OpenRewrite.Recipes.CodeQuality.Simplification.SimplifyBooleanComparison
- Simplify boolean comparison
- Simplify
true == xtox,false == xto!x,true != xto!x, andfalse != xtox.
- OpenRewrite.Recipes.CodeQuality.Simplification.SimplifyCoalesceExpression
- Simplify coalesce expression
- Simplify x ?? x to x.
- OpenRewrite.Recipes.CodeQuality.Simplification.SimplifyCodeBranching
- Simplify code branching
- Simplify code branching patterns such as empty if-else, while(true) with break, and trailing return/continue in if-else.
- OpenRewrite.Recipes.CodeQuality.Simplification.SimplifyConditionalExpression
- Simplify conditional expression
- Simplify
cond ? true : falsetocondandcond ? false : trueto!cond.
- OpenRewrite.Recipes.CodeQuality.Simplification.SimplifyDoWhileToWhile
- Simplify do-while(true) to while(true)
- Convert
do \{ ... \} while (true)towhile (true) \{ ... \}.
- OpenRewrite.Recipes.CodeQuality.Simplification.SimplifyLazyInitialization
- Simplify lazy initialization
- Simplify lazy initialization using ??= operator.
- OpenRewrite.Recipes.CodeQuality.Simplification.SimplifyLogicalNegation
- Simplify logical negation
- Simplify negated comparison expressions. For example,
!(x == y)becomesx != y.
- OpenRewrite.Recipes.CodeQuality.Simplification.SimplifyNegatedIsNull
- Simplify negated is null pattern
- Simplify
!(x is null)tox is not nulland!(x is not null)tox is null.
- OpenRewrite.Recipes.CodeQuality.Simplification.SimplifyNestedUsingStatement
- Simplify nested using statement
- Merge nested
usingstatements into a singleusingdeclaration.
- OpenRewrite.Recipes.CodeQuality.Simplification.SimplifyNullableHasValue
- Simplify Nullable<T>.HasValue
- Replace
x.HasValuewithx != nulland!x.HasValuewithx == null.
- OpenRewrite.Recipes.CodeQuality.Simplification.SimplifyNullableToShorthand
- Simplify Nullable<T> to T?
- Use T? shorthand instead of Nullable<T>.
- OpenRewrite.Recipes.CodeQuality.Simplification.SimplifyNumericComparison
- Simplify numeric comparison
- Simplify
x - y > 0tox > y,x - y < 0tox < y,x - y >= 0tox >= y, andx - y <= 0tox <= y.
- OpenRewrite.Recipes.CodeQuality.Simplification.SimplifyRedundantWhereWhere
- Merge consecutive Where calls
- Detect consecutive
.Where(p).Where(q)calls that could be merged.
- OpenRewrite.Recipes.CodeQuality.Simplification.UnconstrainedTypeParamNullCheck
- Unconstrained type parameter checked for null
- Find null checks on unconstrained type parameters, which may not be reference types.
- OpenRewrite.Recipes.CodeQuality.Simplification.UnnecessaryOperator
- Operator is unnecessary
- Remove unnecessary operators such as unary plus.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseAnonymousFunctionOrMethodGroup
- Use anonymous function or method group
- Convert a lambda expression to a method group where appropriate.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseCoalesceExpression
- Use coalesce expression
- Replace
x != null ? x : yandx == null ? y : xwithx ?? y.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseCoalesceExpressionInsteadOfIf
- Use coalesce expression instead of 'if'
- Replace
if (x == null) x = y;withx ??= y.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseCompoundAssignment
- Use compound assignment
- Replace
x = x op ywithx op= yfor arithmetic, bitwise, shift, and null-coalescing operators.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseConditionalAccess
- Use conditional access
- Transform null-check patterns to use conditional access (?.).
- OpenRewrite.Recipes.CodeQuality.Simplification.UseConditionalAccessInsteadOfIf
- Use conditional access instead of conditional expression
- Transform ternary null-check expressions to use conditional access (?.) with null-coalescing (??) where needed.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseConditionalExpressionForDeclaration
- Use conditional expression in declaration
- Convert
int x; if (cond) x = a; else x = b;toint x = cond ? a : b;.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseConditionalExpressionForReturn
- Use conditional return expression
- Convert
if (c) return a; return b;toreturn c ? a : b;.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseConditionalExpressionForThrow
- Use conditional throw expression
- Detect
if (x == null) throw ...patterns that could usex ?? throw ....
- OpenRewrite.Recipes.CodeQuality.Simplification.UseDateTimeOffsetUnixEpoch
- Use DateTimeOffset.UnixEpoch
- Replace
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero)withDateTimeOffset.UnixEpoch. Available since .NET 8,DateTimeOffset.UnixEpochis more readable.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseDateTimeUnixEpoch
- Use DateTime.UnixEpoch
- Replace
new DateTime(1970, 1, 1)withDateTime.UnixEpoch. Available since .NET 8,DateTime.UnixEpochis more readable and avoids magic numbers.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseDefaultLiteral
- Use default literal
- Simplify default(T) expressions to default. Note: in rare cases where the type cannot be inferred (e.g., overload resolution), manual review may be needed.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseExceptionFilter
- Use exception filter
- Detect catch blocks with if/throw pattern that could use a when clause.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseExpressionBodiedLambda
- Use expression-bodied lambda
- Convert block-body lambdas with a single statement to expression-body lambdas.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseForInsteadOfWhile
- Use for statement instead of while
- Convert while loops with counter to for loops.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseGuidEmpty
- Use Guid.Empty
- Replace
new Guid()withGuid.Empty. The staticGuid.Emptyfield avoids unnecessary allocations and clearly expresses intent.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseIsOperatorInsteadOfAs
- Use 'is' operator instead of 'as' operator
- Replace 'as' operator followed by null check with 'is' operator.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseIsPatternInsteadOfSequenceEqual
- Use 'is' pattern instead of SequenceEqual
- Replace
span.SequenceEqual("str")withspan is "str". Pattern matching with string constants is more concise for span comparisons.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseNotPattern
- Use 'not' pattern instead of negation
- Detect
!(x is Type)patterns that can usex is not Type.
- OpenRewrite.Recipes.CodeQuality.Simplification.UsePatternMatchingForEquality
- Use pattern matching for equality comparison
- Replace
x == constantwithx is constantfor improved readability using C# pattern matching.
- OpenRewrite.Recipes.CodeQuality.Simplification.UsePatternMatchingForInequality
- Use pattern matching for inequality comparison
- Replace
x != constantwithx is not constantfor improved readability using C# pattern matching.
- OpenRewrite.Recipes.CodeQuality.Simplification.UsePatternMatchingInsteadOfAs
- Use pattern matching instead of as
- Use pattern matching instead of as. Note: Needs type resolution.
- OpenRewrite.Recipes.CodeQuality.Simplification.UsePatternMatchingInsteadOfHasValue
- Use pattern matching instead of HasValue
- Replace
nullable.HasValuewithnullable is not null. Pattern matching is more idiomatic in modern C#. Note: this recipe uses name-based matching and may match non-Nullable types with aHasValueproperty.
- OpenRewrite.Recipes.CodeQuality.Simplification.UsePatternMatchingInsteadOfIs
- Use pattern matching instead of is
- Use pattern matching instead of is. Note: Needs type resolution.
- OpenRewrite.Recipes.CodeQuality.Simplification.UsePatternMatchingNullCheck
- Use pattern matching for null check
- Replace
x == nullwithx is nullandx != nullwithx is not null.
- OpenRewrite.Recipes.CodeQuality.Simplification.UsePostfixIncrement
- Use postfix increment/decrement
- Replace
x = x + 1withx++andx = x - 1withx--.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseRangeOperator
- Use range operator
- Detect Substring calls that could use C# 8 range syntax.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseShortCircuitOperator
- Use short-circuit operator
- Replace bitwise
&with&&and|with||in boolean contexts.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseStringEndsWith
- Use string.EndsWith
- Detect substring comparison patterns that could use EndsWith.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseStringEquals
- Use string.Equals instead of == for string comparison
- Replace
==string comparisons withstring.Equals(a, b, StringComparison.Ordinal)for explicit comparison semantics.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseStringInterpolation
- Use string interpolation instead of string.Format
- Replace simple
string.Format("\{0\}", x)calls with$"\{x\}".
- OpenRewrite.Recipes.CodeQuality.Simplification.UseStringInterpolationInsteadOfConcat
- Use string interpolation instead of concatenation
- Replace string.Concat with string interpolation.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseStringStartsWith
- Use string.StartsWith instead of IndexOf comparison
- Replace
s.IndexOf(x) == 0withs.StartsWith(x).
- OpenRewrite.Recipes.CodeQuality.Simplification.UseSwitchExpression
- Use switch expression
- Convert simple switch statements to switch expressions (C# 8+).
- OpenRewrite.Recipes.CodeQuality.Simplification.UseThrowExpression
- Use throw expression
- Convert null-check-then-throw patterns to throw expressions.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseTimeSpanZero
- Use TimeSpan.Zero
- Replace
new TimeSpan(0)andTimeSpan.FromX(0)withTimeSpan.Zero. The staticTimeSpan.Zerofield is more readable and avoids unnecessary object creation.
- OpenRewrite.Recipes.CodeQuality.Simplification.UseXorForBooleanInequality
- Use ^ operator for boolean inequality
- Replace a != b with a ^ b when both operands are boolean.
- OpenRewrite.Recipes.CodeQuality.Style.AbstractTypeShouldNotHavePublicConstructors
- Abstract type should not have public constructors
- Change public constructors of abstract types to protected.
- OpenRewrite.Recipes.CodeQuality.Style.AddParenthesesForClarity
- Add parentheses for clarity
- Add parentheses to expressions where operator precedence might be unclear to improve readability.
- OpenRewrite.Recipes.CodeQuality.Style.AddParenthesesToConditionalExpression
- Add parentheses to conditional expression condition
- Add or remove parentheses from the condition in a conditional operator.
- OpenRewrite.Recipes.CodeQuality.Style.AddRemoveTrailingComma
- Add trailing comma to last enum member
- Add trailing comma to the last member of enum declarations for cleaner diffs when adding new members.
- OpenRewrite.Recipes.CodeQuality.Style.AddStaticToMembersOfStaticClass
- Add static modifier to all members of static class
- Ensure all members of a static class are also declared static.
- OpenRewrite.Recipes.CodeQuality.Style.AddTrailingComma
- Add trailing comma
- Add trailing commas to multi-line initializers and enum declarations for cleaner diffs.
- OpenRewrite.Recipes.CodeQuality.Style.AvoidChainOfAssignments
- Avoid chain of assignments
- Flag chained assignment expressions like a = b = c = value.
- OpenRewrite.Recipes.CodeQuality.Style.AvoidNestingTernary
- Avoid nested ternary operator
- Replace nested ternary expressions with if/else chains for clarity.
- OpenRewrite.Recipes.CodeQuality.Style.CallExtensionMethodAsInstance
- Call extension method as instance method
- Use instance method syntax instead of static extension method call.
- OpenRewrite.Recipes.CodeQuality.Style.CompositeEnumContainsUndefinedFlag
- Composite enum value contains undefined flag
- Find composite enum values that contain a flag which is not defined in the enum type.
- OpenRewrite.Recipes.CodeQuality.Style.ConstantValuesOnRightSide
- Place constant values on right side of comparisons
- Move constant values (literals, null) from the left side of comparisons to the right side for consistency and readability.
- OpenRewrite.Recipes.CodeQuality.Style.ConvertCommentToDocComment
- Convert comment to documentation comment
- Convert single-line or multi-line comments above declarations to XML documentation comments.
- OpenRewrite.Recipes.CodeQuality.Style.DeclareEachAttributeSeparately
- Declare each attribute separately
- Declare each attribute in a separate attribute list.
- OpenRewrite.Recipes.CodeQuality.Style.DeclareEachTypeInSeparateFile
- Declare each type in separate file
- Declare each type in a separate file.
- OpenRewrite.Recipes.CodeQuality.Style.DeclareEachTypeSeparately
- Declare each type in separate file
- Flag files containing multiple top-level type declarations.
- OpenRewrite.Recipes.CodeQuality.Style.DeclareEnumMemberWithZeroValue
- Declare enum member with zero value
- Ensure [Flags] enums have a member explicitly assigned the value 0.
- OpenRewrite.Recipes.CodeQuality.Style.DeclareEnumValueAsCombination
- Declare enum value as combination of names
- Declare Flags enum values as combinations of named values.
- OpenRewrite.Recipes.CodeQuality.Style.DeclareUsingDirectiveOnTopLevel
- Declare using directive on top level
- Move using directives outside of namespace declarations to the top level of the file.
- OpenRewrite.Recipes.CodeQuality.Style.DefaultLabelShouldBeLast
- Default label should be last
- Move default label to the last position in switch statement.
- OpenRewrite.Recipes.CodeQuality.Style.DuplicateEnumValue
- Flag duplicate enum value
- Flag enum members that have the same underlying value.
- OpenRewrite.Recipes.CodeQuality.Style.DuplicateWordInComment
- Duplicate word in a comment
- Find and fix duplicate consecutive words in comments.
- OpenRewrite.Recipes.CodeQuality.Style.EnumShouldDeclareExplicitValues
- Enum should declare explicit values
- Add explicit values to enum members that do not have them.
- OpenRewrite.Recipes.CodeQuality.Style.FindArgumentExceptionParameterName
- ArgumentException should specify argument name
- When throwing
ArgumentExceptionor derived types, specify the parameter name usingnameof().
- OpenRewrite.Recipes.CodeQuality.Style.FindAsyncMethodReturnsNull
- Find async void method
- Detect
async voidmethods. Useasync Taskinstead so callers can await and exceptions propagate correctly.
- OpenRewrite.Recipes.CodeQuality.Style.FindAsyncVoidDelegate
- Find async void delegate
- Detect async lambdas used as delegates where the return type is void. Use
Func<Task>instead ofActionfor async delegates.
- OpenRewrite.Recipes.CodeQuality.Style.FindAvoidAnonymousDelegateForUnsubscribe
- Do not use anonymous delegates to unsubscribe from events
- Unsubscribing from events using anonymous delegates or lambdas has no effect because each lambda creates a new delegate instance.
- OpenRewrite.Recipes.CodeQuality.Style.FindAwaitTaskBeforeDisposing
- Find unawaited task return in using block
- Detect
returnof a Task inside ausingblock withoutawait. The resource may be disposed before the task completes.
- OpenRewrite.Recipes.CodeQuality.Style.FindBothConditionSidesIdentical
- Find binary expression with identical sides
- Detect binary expressions where both sides are identical, e.g.
x == xora && a. This is likely a copy-paste bug.
- OpenRewrite.Recipes.CodeQuality.Style.FindClassWithEqualsButNoIEquatable
- Find class with Equals(T) but no IEquatable<T>
- Detect classes that define
Equals(T)but do not implementIEquatable<T>. Implementing the interface ensures consistency and enables value-based equality.
- OpenRewrite.Recipes.CodeQuality.Style.FindCompareToWithoutIComparable
- Find CompareTo without IComparable
- Detect classes that provide a
CompareTomethod but do not implementIComparable<T>.
- OpenRewrite.Recipes.CodeQuality.Style.FindDangerousThreadingMethods
- Do not use dangerous threading methods
- Avoid
Thread.Abort(),Thread.Suspend(), andThread.Resume(). These methods are unreliable and can corrupt state.
- OpenRewrite.Recipes.CodeQuality.Style.FindDefaultParameterValueNeedsOptional
- Find [DefaultParameterValue] without [Optional]
- Detect parameters with
[DefaultParameterValue]that are missing[Optional]. Both attributes are needed for COM interop default parameter behavior.
- OpenRewrite.Recipes.CodeQuality.Style.FindDoNotCallVirtualMethodInConstructor
- Find virtual method call in constructor
- Detect calls to virtual or abstract methods within constructors. Derived classes may not be fully initialized when these methods execute.
- OpenRewrite.Recipes.CodeQuality.Style.FindDoNotCompareWithNaN
- Find comparison with NaN
- Detect comparisons with
NaNusing==or!=. Usedouble.IsNaN()orfloat.IsNaN()instead, asx == NaNis always false.
- OpenRewrite.Recipes.CodeQuality.Style.FindDoNotCreateTypeWithBCLName
- Find type with BCL name
- Detect class declarations that use names from well-known BCL types like
Task,Action,String, which can cause confusion.
- OpenRewrite.Recipes.CodeQuality.Style.FindDoNotDeclareStaticMembersOnGenericTypes
- Find static members on generic types
- Detect static members declared on generic types. Static members on generic types require specifying type arguments at the call site, reducing discoverability.
- OpenRewrite.Recipes.CodeQuality.Style.FindDoNotOverwriteParameterValue
- Find overwritten parameter values
- Detect assignments to method parameters, which can mask the original argument and lead to confusion.
- OpenRewrite.Recipes.CodeQuality.Style.FindDoNotPassNullForCancellationToken
- Find null passed for CancellationToken
- Detect
nullordefaultpassed forCancellationTokenparameters. UseCancellationToken.Noneinstead.
- OpenRewrite.Recipes.CodeQuality.Style.FindDoNotRaiseApplicationException
- Do not raise ApplicationException
- Avoid throwing
ApplicationException. Use a more specific exception type.
- OpenRewrite.Recipes.CodeQuality.Style.FindDoNotRaiseNotImplementedException
- Do not throw NotImplementedException
- Throwing
NotImplementedExceptionindicates incomplete implementation. Implement the functionality or throw a more specific exception.
- OpenRewrite.Recipes.CodeQuality.Style.FindDoNotRaiseReservedExceptionType
- Do not raise reserved exception types
- Avoid throwing
Exception,SystemException, orApplicationException. Use more specific exception types.
- OpenRewrite.Recipes.CodeQuality.Style.FindDoNotThrowFromFinalizer
- Find throw statements in finalizer
- Detect
throwstatements inside finalizer/destructor methods. Throwing from a finalizer can terminate the process.
- OpenRewrite.Recipes.CodeQuality.Style.FindDoNotThrowFromFinallyBlock
- Do not throw from finally block
- Throwing from a
finallyblock can mask the original exception and make debugging difficult.
- OpenRewrite.Recipes.CodeQuality.Style.FindDoNotUseCertificateValidationCallback
- Do not write custom certificate validation
- Custom certificate validation callbacks can introduce security vulnerabilities by accidentally accepting invalid certificates.
- OpenRewrite.Recipes.CodeQuality.Style.FindDoNotUseEqualityComparerDefaultOfString
- Find EqualityComparer<string>.Default
- Detect
EqualityComparer<string>.Defaultwhich may use different comparison semantics across platforms. Use an explicitStringComparer.
- OpenRewrite.Recipes.CodeQuality.Style.FindDoNotUseGetHashCodeForString
- Find GetType() on Type instance
- Detect
.GetType()called on an object that is already aSystem.Type. Usetypeof()directly.
- OpenRewrite.Recipes.CodeQuality.Style.FindDoNotUseObjectToString
- Find ToString on object-typed parameter
- Detect
.ToString()calls onobject-typed parameters. The defaultobject.ToString()returns the type name, which is rarely the intended behavior.
- OpenRewrite.Recipes.CodeQuality.Style.FindDoNotUseSleep
- Find Thread.Sleep usage
- Detect
Thread.Sleep()which blocks the thread. Useawait Task.Delay()in async contexts instead.
- OpenRewrite.Recipes.CodeQuality.Style.FindDoNotUseStringGetHashCode
- Find string.GetHashCode() usage
- Detect
string.GetHashCode()which is not stable across runs. UseStringComparer.GetHashCode()orstring.GetHashCode(StringComparison)instead.
- OpenRewrite.Recipes.CodeQuality.Style.FindEmbedCaughtExceptionAsInner
- Embed caught exception as inner exception
- When rethrowing a different exception in a catch block, pass the original exception as the inner exception to preserve the stack trace.
- OpenRewrite.Recipes.CodeQuality.Style.FindEnumDefaultValueZero
- Find explicit zero initialization in enum
- Detect enum members explicitly initialized to
0. The default value of an enum is already0.
- OpenRewrite.Recipes.CodeQuality.Style.FindEqualsWithoutNotNullWhen
- Find Equals without [NotNullWhen(true)]
- Detect
Equals(object?)overrides that are missing[NotNullWhen(true)]on the parameter, which helps nullable analysis.
- OpenRewrite.Recipes.CodeQuality.Style.FindEventArgsSenderNotNull
- Find event raised with null EventArgs
- Detect event invocations that pass
nullfor EventArgs. UseEventArgs.Emptyinstead.
- OpenRewrite.Recipes.CodeQuality.Style.FindFlowCancellationTokenInAwaitForEach
- Find await foreach without CancellationToken
- Detect
await foreachloops that don't pass aCancellationTokenviaWithCancellation()when one is available in the enclosing method.
- OpenRewrite.Recipes.CodeQuality.Style.FindIComparableWithoutComparisonOperators
- Find IComparable without comparison operators
- Detect classes that implement
IComparable<T>but do not override comparison operators (<,>,<=,>=).
- OpenRewrite.Recipes.CodeQuality.Style.FindIComparableWithoutIEquatable
- Find IComparable<T> without IEquatable<T>
- Detect classes that implement
IComparable<T>but notIEquatable<T>. Both interfaces should be implemented together for consistent comparison semantics.
- OpenRewrite.Recipes.CodeQuality.Style.FindIEquatableWithoutEquals
- Find IEquatable<T> without Equals(object) override
- Detect classes that implement
IEquatable<T>but do not overrideEquals(object), which can lead to inconsistent equality behavior.
- OpenRewrite.Recipes.CodeQuality.Style.FindILoggerTypeMismatch
- Find ILogger<T> type parameter mismatch
- Detect
ILogger<T>fields or parameters whereTdoesn't match the containing type name.
- OpenRewrite.Recipes.CodeQuality.Style.FindIfElseBranchesIdentical
- Find if/else with identical branches
- Detect
if/elsestatements where both branches contain identical code. This is likely a copy-paste bug.
- OpenRewrite.Recipes.CodeQuality.Style.FindImplementNonGenericInterface
- Find missing non-generic interface implementation
- Detect types implementing
IComparable<T>withoutIComparable, orIEquatable<T>without proper Equals override.
- OpenRewrite.Recipes.CodeQuality.Style.FindImplicitCultureSensitiveToStringDirect
- Find implicit culture-sensitive ToString in concatenation
- Detect string concatenation with numeric types that implicitly call culture-sensitive
ToString(). Use an explicit format orCultureInfo.InvariantCulture.
- OpenRewrite.Recipes.CodeQuality.Style.FindImplicitDateTimeOffsetConversion
- Find implicit DateTime to DateTimeOffset conversion
- Detect implicit conversion from
DateTimetoDateTimeOffsetwhich uses the local time zone and can produce unexpected results.
- OpenRewrite.Recipes.CodeQuality.Style.FindInterpolatedStringWithoutParameters
- Find interpolated string without parameters
- Detect interpolated strings (
$"...") that contain no interpolation expressions. Use a regular string literal instead.
- OpenRewrite.Recipes.CodeQuality.Style.FindInvalidAttributeArgumentType
- Find potentially invalid attribute argument type
- Detect attribute arguments that use types not valid in attribute constructors (only primitives, string, Type, enums, and arrays of these are allowed).
- OpenRewrite.Recipes.CodeQuality.Style.FindMethodReturningIAsyncEnumerable
- Find IAsyncEnumerable method without Async suffix
- Detect methods returning
IAsyncEnumerable<T>that don't end withAsync.
- OpenRewrite.Recipes.CodeQuality.Style.FindMethodTooLong
- Find method that is too long
- Detect methods with more than 60 statements. Long methods are harder to understand and maintain.
- OpenRewrite.Recipes.CodeQuality.Style.FindMissingCancellationTokenOverload
- Find async call missing CancellationToken
- Detect async method calls that don't pass a
CancellationTokenwhen the enclosing method has one available as a parameter.
- OpenRewrite.Recipes.CodeQuality.Style.FindMissingNamedParameter
- Find boolean literal arguments without parameter name
- Detect method calls passing
trueorfalseliterals as arguments. Using named parameters improves readability.
- OpenRewrite.Recipes.CodeQuality.Style.FindMissingParamsInOverride
- Find override method missing params keyword
- Detect override methods that may be missing the
paramskeyword on array parameters that the base method declares asparams.
- OpenRewrite.Recipes.CodeQuality.Style.FindMissingStringComparison
- Find string method missing StringComparison
- Detect string methods like
Equals,Contains,StartsWith,EndsWithcalled without an explicitStringComparisonparameter.
- OpenRewrite.Recipes.CodeQuality.Style.FindMissingStringEqualityComparer
- Find missing string equality comparer
- Detect
Dictionary<string, T>andHashSet<string>created without an explicitStringComparer. Without a comparer, the default ordinal comparison is used.
- OpenRewrite.Recipes.CodeQuality.Style.FindMultiLineXmlComment
- Find multi-line XML doc comments
- Detect
/** */style XML documentation comments that could use the///single-line syntax for consistency.
- OpenRewrite.Recipes.CodeQuality.Style.FindNonConstantStaticFieldsVisible
- Non-constant static fields should not be visible
- Public static fields that are not
constorreadonlycan be modified by any code, breaking encapsulation. Make themreadonlyor use a property.
- OpenRewrite.Recipes.CodeQuality.Style.FindNonDeterministicEndOfLine
- Find non-deterministic end-of-line in strings
- Detect string literals containing
\nthat may behave differently across platforms. Consider usingEnvironment.NewLineinstead.
- OpenRewrite.Recipes.CodeQuality.Style.FindNonFlagsEnumWithFlagsAttribute
- Find non-flags enum with [Flags]
- Detect enums marked with
[Flags]whose values are not powers of two, indicating they are not truly flags enums.
- OpenRewrite.Recipes.CodeQuality.Style.FindNotNullIfNotNullAttribute
- Find missing NotNullIfNotNull attribute
- Detect methods with nullable return types depending on nullable parameters that lack
[NotNullIfNotNull]attribute.
- OpenRewrite.Recipes.CodeQuality.Style.FindObserveAsyncResult
- Find unobserved async call result
- Detect calls to async methods where the returned Task is not awaited, assigned, or otherwise observed. Unobserved tasks may silently swallow exceptions.
- OpenRewrite.Recipes.CodeQuality.Style.FindObsoleteWithoutMessage
- Obsolete attribute should include explanation
- The
[Obsolete]attribute should include a message explaining why the member is obsolete and what to use instead.
- OpenRewrite.Recipes.CodeQuality.Style.FindOverrideChangesParameterDefaults
- Find overrides that change parameter defaults
- Detect
overridemethods with default parameter values. Overrides should not change defaults from the base method as this causes confusing behavior depending on the reference type.
- OpenRewrite.Recipes.CodeQuality.Style.FindPreferCollectionAbstraction
- Find concrete collection in public API
- Detect public method parameters or return types that use concrete collection types like
List<T>instead ofIList<T>orIEnumerable<T>.
- OpenRewrite.Recipes.CodeQuality.Style.FindPrimaryConstructorReadonly
- Find reassigned primary constructor parameter
- Detect primary constructor parameters that are reassigned in the class body. Primary constructor parameters should be treated as readonly.
- OpenRewrite.Recipes.CodeQuality.Style.FindRawStringImplicitEndOfLine
- Find raw string with implicit end of line
- Detect raw string literals (
"""...""") that contain implicit end-of-line characters which may behave differently across platforms.
- OpenRewrite.Recipes.CodeQuality.Style.FindReadOnlyStructMembers
- Find struct member that could be readonly
- Detect struct methods and properties that don't modify state and could be marked
readonlyto prevent defensive copies.
- OpenRewrite.Recipes.CodeQuality.Style.FindRedundantArgumentValue
- Find redundant default argument values
- Detect named arguments that explicitly pass a default value. Removing them simplifies the call.
- OpenRewrite.Recipes.CodeQuality.Style.FindSenderNullForStaticEvents
- Find static event with non-null sender
- Detect static event invocations that pass
thisas the sender. Static events should usenullas the sender.
- OpenRewrite.Recipes.CodeQuality.Style.FindSingleLineXmlComment
- Find multi-line XML doc comment style
- Detect
/** ... */style XML doc comments. Use///single-line style instead for consistency.
- OpenRewrite.Recipes.CodeQuality.Style.FindSpanEqualityOperator
- Find equality operator on Span<T>
- Detect
==or!=operators onSpan<T>orReadOnlySpan<T>. UseSequenceEqualinstead.
- OpenRewrite.Recipes.CodeQuality.Style.FindStreamReadIgnored
- Find Stream.Read() return value ignored
- Detect
Stream.Read()calls where the return value (bytes read) is not used. This can lead to incomplete reads.
- OpenRewrite.Recipes.CodeQuality.Style.FindStringFormatConstant
- Find non-constant string.Format format string
- Detect non-constant format strings passed to
string.Format. Use a constant to prevent format string injection.
- OpenRewrite.Recipes.CodeQuality.Style.FindTaskInUsing
- Find unawaited task in using statement
- Detect
usingstatements where a Task is not awaited, which can cause premature disposal before the task completes.
- OpenRewrite.Recipes.CodeQuality.Style.FindThreadStaticOnInstanceField
- Do not use ThreadStatic on instance fields
[ThreadStatic]only works on static fields. Using it on instance fields has no effect.
- OpenRewrite.Recipes.CodeQuality.Style.FindThrowIfNullWithNonNullable
- Find ThrowIfNull with value type argument
- Detect
ArgumentNullException.ThrowIfNullcalled with value type parameters that can never be null.
- OpenRewrite.Recipes.CodeQuality.Style.FindTypeNameMatchesNamespace
- Find type name matching namespace
- Detect type names that match their containing namespace, which can cause ambiguous references.
- OpenRewrite.Recipes.CodeQuality.Style.FindTypeShouldNotExtendApplicationException
- Types should not extend ApplicationException
- Do not create custom exceptions that inherit from
ApplicationException. Inherit fromExceptionor a more specific exception type.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseCallerArgumentExpression
- Find redundant nameof with CallerArgumentExpression
- Detect
nameof(param)passed to parameters marked with[CallerArgumentExpression]. The attribute fills the value automatically.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseDateTimeOffsetInsteadOfDateTime
- Find DateTime.Now/UtcNow usage
- Detect
DateTime.NowandDateTime.UtcNowusage. UseDateTimeOffsetinstead for unambiguous time representation across time zones.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseDebuggerDisplayAttribute
- Find ToString override without DebuggerDisplay
- Detect classes that override
ToString()but lack[DebuggerDisplay]attribute for debugger integration.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseDefaultParameterValue
- Find [DefaultValue] on parameter
- Detect
[DefaultValue]on method parameters. Use[DefaultParameterValue]instead, as[DefaultValue]is for component model metadata only.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseElementAccessInsteadOfLinq
- Find ElementAt() that could use indexer
- Detect LINQ
.ElementAt(index)calls that could be replaced with direct indexer access[index].
- OpenRewrite.Recipes.CodeQuality.Style.FindUseEqualsMethodInsteadOfOperator
- Find == comparison that should use Equals()
- Detect
==comparisons on reference types that overrideEquals. Using==may compare references instead of values.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseExplicitEnumValue
- Find integer 0 used instead of named enum value
- Detect usage of integer literal
0where a named enum member should be used for clarity.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseFormatProviderInToString
- Find Parse/ToString without IFormatProvider
- Detect calls to culture-sensitive methods like
int.Parse,double.Parsewithout an explicitIFormatProviderorCultureInfo.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseIFormatProvider
- Find Parse/TryParse without IFormatProvider
- Detect
int.Parse(str)and similar calls without anIFormatProviderparameter. UseCultureInfo.InvariantCulturefor culture-independent parsing.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseLangwordInXmlComment
- Find missing langword in XML comment
- Detect XML doc comments that reference
null,true,falseas plain text instead of using<see langword="..."/>.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseLazyInitializerEnsureInitialize
- Find Interlocked.CompareExchange lazy init pattern
- Detect
Interlocked.CompareExchange(ref field, new T(), null)pattern. UseLazyInitializer.EnsureInitializedfor cleaner lazy initialization.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseListPatternMatching
- Find collection emptiness check
- Detect
.Length == 0or.Count == 0checks that could use list patterns likeis []in C# 11+.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseNamedParameter
- Find boolean literal argument without name
- Detect boolean literal arguments (
true/false) passed without named parameters. Named arguments improve readability.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseOperatingSystemMethods
- Use OperatingSystem methods instead of RuntimeInformation
- Use
OperatingSystem.IsWindows()and similar methods instead ofRuntimeInformation.IsOSPlatform(). The OperatingSystem methods are more concise and can be optimized by the JIT.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseProcessStartWithStartInfo
- Find Process.Start with string argument
- Detect
Process.Start("filename")which should use theProcessStartInfooverload for explicit control overUseShellExecuteand other settings.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseRecordClassExplicitly
- Find implicit record class declaration
- Detect
recorddeclarations that should userecord classexplicitly to clarify that they are reference types.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseRegexOptions
- Find Regex without ExplicitCapture option
- Detect
new Regex()orRegex.IsMatch()withoutRegexOptions.ExplicitCapture. Using this option avoids unnecessary unnamed captures.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseShellExecuteFalseWhenRedirecting
- Find redirect without UseShellExecute=false
- Detect
ProcessStartInfothat setsRedirectStandard*without explicitly settingUseShellExecute = false.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseShellExecuteNotSet
- Find ProcessStartInfo without UseShellExecute
- Detect
new ProcessStartInfo()without explicitly settingUseShellExecute. The default changed between .NET Framework (true) and .NET Core (false).
- OpenRewrite.Recipes.CodeQuality.Style.FindUseStringComparer
- Find Dictionary/HashSet without StringComparer
- Detect
Dictionary<string, T>orHashSet<string>created without an explicitStringComparer. UseStringComparer.OrdinalorStringComparer.OrdinalIgnoreCase.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseStringCreateInsteadOfConcat
- Find FormattableString usage
- Detect
FormattableStringusage. Consider usingString.Createon .NET 6+ for better performance.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseStringEqualsInsteadOfIsPattern
- Find 'is' pattern with string literal
- Detect
x is "literal"patterns that should usestring.Equalswith explicitStringComparisonfor culture-aware or case-insensitive comparisons.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseSystemThreadingLock
- Use System.Threading.Lock instead of object for locking
- In .NET 9+, use
System.Threading.Lockinstead ofobjectfor lock objects. The dedicated Lock type provides better performance.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseTaskUnwrap
- Find double await pattern
- Detect
await awaitpattern which can be replaced with.Unwrap()for clarity.
- OpenRewrite.Recipes.CodeQuality.Style.FindUseTimeProviderInsteadOfCustom
- Find custom time abstraction
- Detect interfaces or abstract classes that appear to be custom time providers. Use
System.TimeProvider(available in .NET 8+) instead.
- OpenRewrite.Recipes.CodeQuality.Style.FindValidateArgumentsBeforeYield
- Find argument validation in iterator method
- Detect iterator methods that validate arguments after
yield return. Argument validation in iterators is deferred until enumeration begins.
- OpenRewrite.Recipes.CodeQuality.Style.ImplementExceptionConstructors
- Implement exception constructors
- Ensure custom exception classes implement standard constructors.
- OpenRewrite.Recipes.CodeQuality.Style.ImplementNonGenericCounterpart
- Implement non-generic counterpart
- Implement non-generic interface when implementing generic counterpart.
- OpenRewrite.Recipes.CodeQuality.Style.InvalidArgumentNullCheck
- Fix invalid argument null check
- Fix invalid argument null check patterns.
- OpenRewrite.Recipes.CodeQuality.Style.MakeClassSealed
- Make class sealed
- A class that has only private constructors should be marked as sealed.
- OpenRewrite.Recipes.CodeQuality.Style.MakeClassStatic
- Make class static
- Make classes that contain only static members static.
- OpenRewrite.Recipes.CodeQuality.Style.MakeFieldReadOnly
- Make field read-only
- Make field read-only when it is only assigned in the constructor or initializer.
- OpenRewrite.Recipes.CodeQuality.Style.MakeMethodExtensionMethod
- Make method an extension method
- Convert a static method to an extension method where appropriate.
- OpenRewrite.Recipes.CodeQuality.Style.MarkLocalVariableAsConst
- Mark local variable as const
- Mark local variable as const when its value never changes.
- OpenRewrite.Recipes.CodeQuality.Style.MarkTypeWithDebuggerDisplay
- Mark type with DebuggerDisplay attribute
- Add DebuggerDisplay attribute to publicly visible types to improve debugging experience.
- OpenRewrite.Recipes.CodeQuality.Style.MergePreprocessorDirectives
- Merge preprocessor directives
- Merge consecutive preprocessor directives that can be combined into a single directive.
- OpenRewrite.Recipes.CodeQuality.Style.NormalizeEnumFlagValue
- Normalize format of enum flag value
- Normalize the format of Flags enum values.
- OpenRewrite.Recipes.CodeQuality.Style.OrderModifiers
- Order modifiers
- Reorder modifiers to the canonical C# order: access, new, abstract/virtual/override/sealed, static, readonly, extern, unsafe, volatile, async, partial, const.
- OpenRewrite.Recipes.CodeQuality.Style.OrderNamedArguments
- Order named arguments by parameters
- Reorder named arguments to match parameter order.
- OpenRewrite.Recipes.CodeQuality.Style.OrderTypeParameterConstraints
- Order type parameter constraints
- Order type parameter constraints consistently.
- OpenRewrite.Recipes.CodeQuality.Style.OverridingMemberShouldNotChangeParams
- Overriding member should not change 'params' modifier
- An overriding member should not add or remove the 'params' modifier compared to its base declaration.
- OpenRewrite.Recipes.CodeQuality.Style.ParameterNameDiffersFromBase
- Parameter name differs from base
- Rename parameter to match base class or interface definition.
- OpenRewrite.Recipes.CodeQuality.Style.ParenthesizeNotPattern
- Parenthesize not pattern for clarity
- Add parentheses to
not A or B→(not A) or Bto clarify thatnotbinds tighter thanor.
- OpenRewrite.Recipes.CodeQuality.Style.PreferNullCheckOverTypeCheck
- Prefer null check over type check
- Replace
x is objectwithx is not nullfor clarity.
- OpenRewrite.Recipes.CodeQuality.Style.SimplifyBooleanLogic
- Simplify boolean logic with constants
- Simplify
x || truetotrue,x && falsetofalse,x || falsetox, andx && truetox.
- OpenRewrite.Recipes.CodeQuality.Style.SortEnumMembers
- Sort enum members
- Sort enum members by their resolved constant value.
- OpenRewrite.Recipes.CodeQuality.Style.SplitVariableDeclaration
- Split variable declaration
- Split multi-variable declarations into separate declarations.
- OpenRewrite.Recipes.CodeQuality.Style.StaticMemberInGenericType
- Static member in generic type should use a type parameter
- Find static members in generic types that do not use any of the type's type parameters.
- OpenRewrite.Recipes.CodeQuality.Style.StyleCodeQuality
- Style code quality
- Code style modernization recipes for C#.
- OpenRewrite.Recipes.CodeQuality.Style.UnusedParameter
- Remove unused parameter
- Rename unused lambda parameters to discard (_).
- OpenRewrite.Recipes.CodeQuality.Style.UnusedTypeParameter
- Remove unused type parameter
- Flag type parameters that are not used.
- OpenRewrite.Recipes.CodeQuality.Style.UseAsyncAwait
- Use async/await when necessary
- Add async/await to methods that return Task but don't use await.
- OpenRewrite.Recipes.CodeQuality.Style.UseAttributeUsageAttribute
- Use AttributeUsageAttribute
- Add AttributeUsage to custom attribute classes.
- OpenRewrite.Recipes.CodeQuality.Style.UseAutoProperty
- Use auto property
- Use auto property instead of property with backing field.
- OpenRewrite.Recipes.CodeQuality.Style.UseBlockBodyOrExpressionBody
- Use block body or expression body
- Convert between block body and expression body for members.
- OpenRewrite.Recipes.CodeQuality.Style.UseCoalesceExpressionFromNullCheck
- Use coalesce expression
- Convert null-check conditional to null-coalescing expression.
- OpenRewrite.Recipes.CodeQuality.Style.UseCollectionExpression
- Use collection expression
- Replace array/list creation with collection expressions (C# 12).
- OpenRewrite.Recipes.CodeQuality.Style.UseConstantInsteadOfField
- Use constant instead of field
- Convert
static readonlyfields with literal initializers toconst.
- OpenRewrite.Recipes.CodeQuality.Style.UseElementAccess
- Use element access
- Use indexer instead of First()/Last()/ElementAt() when the collection supports indexer access.
- OpenRewrite.Recipes.CodeQuality.Style.UseEnumFieldExplicitly
- Use enum field explicitly
- Use named enum field instead of cast integer value.
- OpenRewrite.Recipes.CodeQuality.Style.UseEventArgsEmpty
- Use EventArgs.Empty
- Replace
new EventArgs()withEventArgs.Empty. The staticEventArgs.Emptyfield avoids unnecessary allocations.
- OpenRewrite.Recipes.CodeQuality.Style.UseEventArgsEmptyForNull
- Use EventArgs.Empty instead of null
- Replace
nullwithEventArgs.Emptywhen raising events. Passingnullfor EventArgs can cause NullReferenceException in event handlers.
- OpenRewrite.Recipes.CodeQuality.Style.UseEventHandlerT
- Use EventHandler<T>
- Use generic EventHandler<T> instead of custom delegate types.
- OpenRewrite.Recipes.CodeQuality.Style.UseExplicitTypeInsteadOfVar
- Use explicit type instead of var
- Use explicit type instead of
varwhen the type is not evident.
- OpenRewrite.Recipes.CodeQuality.Style.UseExplicitlyTypedArray
- Use explicitly typed array
- Use explicitly or implicitly typed array.
- OpenRewrite.Recipes.CodeQuality.Style.UseFileScopedNamespace
- Use file-scoped namespace
- Detect block-scoped namespace declarations that could use file-scoped syntax (C# 10).
- OpenRewrite.Recipes.CodeQuality.Style.UseMethodChaining
- Use method chaining
- Chain consecutive method calls on the same receiver into a fluent chain.
- OpenRewrite.Recipes.CodeQuality.Style.UseMethodGroupConversion
- Use method group conversion
- Replace
x => Foo(x)withFoowhere method group conversion applies.
- OpenRewrite.Recipes.CodeQuality.Style.UsePredefinedType
- Use predefined type
- Use predefined type keyword (e.g., int instead of Int32).
- OpenRewrite.Recipes.CodeQuality.Style.UsePrimaryConstructor
- Use primary constructor
- Convert classes with a single constructor into primary constructor syntax (C# 12).
- OpenRewrite.Recipes.CodeQuality.Style.UseReadOnlyAutoProperty
- Use read-only auto property
- Use read-only auto property when the setter is never used.
- OpenRewrite.Recipes.CodeQuality.Style.UseStringContains
- Use string.Contains instead of IndexOf comparison
- Replace
s.IndexOf(x) >= 0withs.Contains(x)ands.IndexOf(x) == -1with!s.Contains(x).
- OpenRewrite.Recipes.CodeQuality.Style.UseStringIsNullOrEmpty
- Use string.IsNullOrEmpty method
- Replace
s == null || s == ""ands == null || s.Length == 0withstring.IsNullOrEmpty(s).
- OpenRewrite.Recipes.CodeQuality.Style.UseStringLengthComparison
- Use string.Length instead of comparison with empty string
- Replace
s == ""withs.Length == 0ands != ""withs.Length != 0.
- OpenRewrite.Recipes.CodeQuality.Style.UseThisForEventSender
- Use 'this' for event sender
- Replace
nullwiththisas the sender argument when raising instance events. The sender should be the object raising the event.
- OpenRewrite.Recipes.CodeQuality.Style.UseUsingDeclaration
- Use using declaration
- Convert using statement to using declaration.
- OpenRewrite.Recipes.CodeQuality.Style.UseVarInForEach
- Use var instead of explicit type in foreach
- Replace explicit type in foreach with var when type is evident.
- OpenRewrite.Recipes.CodeQuality.Style.UseVarOrExplicitType
- Use 'var' or explicit type
- Enforce consistent use of 'var' or explicit type in local variable declarations.
- OpenRewrite.Recipes.CodeQuality.Style.ValidateArgumentsCorrectly
- Validate arguments correctly
- Ensure argument validation in iterator methods runs immediately by flagging iterator methods that contain argument validation.
- OpenRewrite.Recipes.CodeQuality.Style.ValueTypeIsNeverEqualToNull
- Value type is never equal to null
- Replace null with default in comparisons of value types.
- OpenRewrite.Xml.Recipes.ChangeXmlAttribute
- Change XML attribute value
- Changes the value of attributes matching AttrName to NewValue.
- OpenRewrite.Xml.Recipes.ChangeXmlCharData
- Change XML CharData text
- Replaces occurrences of OldText with NewText in XML CharData nodes.
recipes-migrate-dotnet
- OpenRewrite.Recipes.AddNuGetPackageReference
- Add NuGet package reference
- Adds a
<PackageReference>to .csproj files if not already present.
- OpenRewrite.Recipes.AspNet.UpgradeAspNetFrameworkToCore
- Migrate ASP.NET Framework to ASP.NET Core
- Migrate ASP.NET Framework (System.Web.Mvc, System.Web.Http) types to their ASP.NET Core equivalents. Based on the .NET Upgrade Assistant's UA0002 and UA0010 diagnostics. See https://learn.microsoft.com/en-us/aspnet/core/migration/proper-to-2x.
- OpenRewrite.Recipes.AspNetCore2.FindBuildWebHost
- Find BuildWebHost method
- Flags
BuildWebHostmethod declarations that should be renamed toCreateWebHostBuilderand refactored for ASP.NET Core 2.1.
- OpenRewrite.Recipes.AspNetCore2.FindIAuthenticationManager
- Find IAuthenticationManager usage
- Flags references to
IAuthenticationManagerwhich was removed in ASP.NET Core 2.0. UseHttpContextextension methods fromMicrosoft.AspNetCore.Authenticationinstead.
- OpenRewrite.Recipes.AspNetCore2.FindLoggerFactoryAddProvider
- Find ILoggerFactory.Add() calls*
- Flags
ILoggerFactory.AddConsole(),AddDebug(), and similar extension methods. In ASP.NET Core 2.2+, logging should be configured viaConfigureLoggingin the host builder.
- OpenRewrite.Recipes.AspNetCore2.FindSetCompatibilityVersion
- Find SetCompatibilityVersion() calls
- Flags
SetCompatibilityVersioncalls. This method is a no-op in ASP.NET Core 3.0+ and should be removed during migration.
- OpenRewrite.Recipes.AspNetCore2.FindUseKestrelWithConfig
- Find UseKestrel() with configuration
- Flags
UseKestrelcalls with configuration lambdas that should be replaced withConfigureKestrelto avoid conflicts with the IIS in-process hosting model.
- OpenRewrite.Recipes.AspNetCore2.UpgradeToAspNetCore20
- Migrate to ASP.NET Core 2.0
- Migrate ASP.NET Core 1.x projects to ASP.NET Core 2.0, applying authentication and Identity changes. See https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x.
- OpenRewrite.Recipes.AspNetCore2.UpgradeToAspNetCore21
- Migrate to ASP.NET Core 2.1
- Migrate ASP.NET Core 2.0 projects to ASP.NET Core 2.1, including host builder changes and obsolete API replacements. See https://learn.microsoft.com/en-us/aspnet/core/migration/20-to-21.
- OpenRewrite.Recipes.AspNetCore2.UpgradeToAspNetCore22
- Migrate to ASP.NET Core 2.2
- Migrate ASP.NET Core 2.1 projects to ASP.NET Core 2.2, including Kestrel configuration and logging changes. See https://learn.microsoft.com/en-us/aspnet/core/migration/21-to-22.
- OpenRewrite.Recipes.AspNetCore2.UseGetExternalAuthenticationSchemesAsync
- Use GetExternalAuthenticationSchemesAsync()
- Replace
GetExternalAuthenticationSchemes()withGetExternalAuthenticationSchemesAsync(). The synchronous method was removed in ASP.NET Core 2.0.
- OpenRewrite.Recipes.AspNetCore2.UseHttpContextAuthExtensions
- Use HttpContext authentication extensions
- Replace
HttpContext.Authentication.Method(...)calls withHttpContext.Method(...)extension methods. TheIAuthenticationManagerinterface was removed in ASP.NET Core 2.0.
- OpenRewrite.Recipes.AspNetCore2.UseUseAuthentication
- Replace UseIdentity() with UseAuthentication()
- Replace
app.UseIdentity()withapp.UseAuthentication(). TheUseIdentitymethod was removed in ASP.NET Core 2.0 in favor ofUseAuthentication.
- OpenRewrite.Recipes.AspNetCore3.FindAddMvc
- Find AddMvc() calls
- Flags
AddMvc()calls that should be replaced with more specific service registrations (AddControllers,AddControllersWithViews, orAddRazorPages) in ASP.NET Core 3.0.
- OpenRewrite.Recipes.AspNetCore3.FindIApplicationLifetime
- Find IApplicationLifetime usage
- Flags usages of
IApplicationLifetimewhich should be replaced withIHostApplicationLifetimein ASP.NET Core 3.0.
- OpenRewrite.Recipes.AspNetCore3.FindIHostingEnvironment
- Find IHostingEnvironment usage
- Flags usages of
IHostingEnvironmentwhich should be replaced withIWebHostEnvironmentin ASP.NET Core 3.0.
- OpenRewrite.Recipes.AspNetCore3.FindNewLoggerFactory
- Find new LoggerFactory() calls
- Flags
new LoggerFactory()calls that should be replaced withLoggerFactory.Create(builder => ...)in .NET Core 3.0+.
- OpenRewrite.Recipes.AspNetCore3.FindNewtonsoftJsonUsage
- Find Newtonsoft.Json usage in ASP.NET Core
- Flags
JsonConvertand otherNewtonsoft.Jsonusage. ASP.NET Core 3.0 usesSystem.Text.Jsonby default.
- OpenRewrite.Recipes.AspNetCore3.FindUseMvcOrUseSignalR
- Find UseMvc()/UseSignalR() calls
- Flags
UseMvc()andUseSignalR()calls that should be replaced with endpoint routing (UseRouting()+UseEndpoints()) in ASP.NET Core 3.0.
- OpenRewrite.Recipes.AspNetCore3.FindWebHostBuilder
- Find WebHostBuilder usage
- Flags
WebHostBuilderandWebHost.CreateDefaultBuilderusage that should migrate to the Generic Host pattern in ASP.NET Core 3.0+.
- OpenRewrite.Recipes.AspNetCore3.UpgradeToAspNetCore30
- Migrate to ASP.NET Core 3.0
- Migrate ASP.NET Core 2.2 projects to ASP.NET Core 3.0, including endpoint routing, Generic Host, and System.Text.Json changes. See https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30.
- OpenRewrite.Recipes.ChangeDotNetTargetFramework
- Change .NET target framework
- Changes the
<TargetFramework>or<TargetFrameworks>value in .csproj files. For multi-TFM projects, replaces the matching framework within the semicolon-delimited list.
- OpenRewrite.Recipes.ChangeMethodName
- Change method name
- Rename a method.
- OpenRewrite.Recipes.ChangeType
- Change type
- Change a type reference to another type.
- OpenRewrite.Recipes.DeleteMethodArgument
- Delete method argument
- Delete an argument from method invocations.
- OpenRewrite.Recipes.Net10.FindActionContextAccessorObsolete
- Find obsolete
IActionContextAccessor/ActionContextAccessor(ASPDEPR006) - Finds usages of
IActionContextAccessorandActionContextAccessorwhich are obsolete in .NET 10. UseIHttpContextAccessorandHttpContext.GetEndpoint()instead.
- Find obsolete
- OpenRewrite.Recipes.Net10.FindActivitySampling
- Find
ActivitySamplingResult.PropagationDatabehavior change - Finds usages of
ActivitySamplingResult.PropagationDatawhich has changed behavior in .NET 10. Activities with a recorded parent and PropagationData sampling no longer setActivity.Recorded = true.
- Find
- OpenRewrite.Recipes.Net10.FindBackgroundServiceExecuteAsync
- Find
BackgroundService.ExecuteAsyncbehavior change - Finds methods that override
ExecuteAsyncfromBackgroundService. In .NET 10, the entire method runs on a background thread; synchronous code before the firstawaitno longer blocks host startup.
- Find
- OpenRewrite.Recipes.Net10.FindBufferedStreamWriteByte
- Find
BufferedStream.WriteByteimplicit flush behavior change - Finds calls to
BufferedStream.WriteByte()which no longer performs an implicit flush when the internal buffer is full in .NET 10. CallFlush()explicitly if needed.
- Find
- OpenRewrite.Recipes.Net10.FindClipboardGetData
- Find obsolete
Clipboard.GetDatacalls (WFDEV005) - Finds calls to
Clipboard.GetData(string). In .NET 10, this method is obsolete (WFDEV005). UseClipboard.TryGetDatamethods instead.
- Find obsolete
- OpenRewrite.Recipes.Net10.FindDistributedContextPropagator
- Find
DistributedContextPropagatordefault propagator change - Finds usages of
DistributedContextPropagator.CurrentandDistributedContextPropagator.CreateDefaultPropagator()which now default to W3C format in .NET 10. The 'baggage' header is used instead of 'Correlation-Context'.
- Find
- OpenRewrite.Recipes.Net10.FindDllImportSearchPath
- Find
DllImportSearchPath.AssemblyDirectorybehavior change - Finds usages of
DllImportSearchPath.AssemblyDirectorywhich has changed behavior in .NET 10. Specifying onlyAssemblyDirectoryno longer falls back to OS default search paths.
- Find
- OpenRewrite.Recipes.Net10.FindDriveInfoDriveFormat
- Find
DriveInfo.DriveFormatbehavior change - Finds usages of
DriveInfo.DriveFormatwhich returns Linux kernel filesystem type strings instead of mapped names in .NET 10. Verify that comparisons match the new format.
- Find
- OpenRewrite.Recipes.Net10.FindFormOnClosingObsolete
- Find obsolete
Form.OnClosing/OnClosedusage (WFDEV004) - Finds usage of
Form.OnClosing,Form.OnClosed, and theClosing/Closedevents. In .NET 10, these are obsolete (WFDEV004). UseOnFormClosing/OnFormClosedandFormClosing/FormClosedinstead.
- Find obsolete
- OpenRewrite.Recipes.Net10.FindGnuTarPaxTarEntry
- Find
GnuTarEntry/PaxTarEntrydefault timestamp change - Finds
new GnuTarEntry(...)andnew PaxTarEntry(...)constructor calls. In .NET 10, these no longer set atime and ctime by default. SetAccessTime/ChangeTimeexplicitly if needed.
- Find
- OpenRewrite.Recipes.Net10.FindIpNetworkObsolete
- Find obsolete
IPNetwork/KnownNetworks(ASPDEPR005) - Finds usages of
Microsoft.AspNetCore.HttpOverrides.IPNetworkandForwardedHeadersOptions.KnownNetworkswhich are obsolete in .NET 10. UseSystem.Net.IPNetworkandKnownIPNetworksinstead.
- Find obsolete
- OpenRewrite.Recipes.Net10.FindKeyedServiceAnyKey
- Find
KeyedService.AnyKeybehavior change - Finds usages of
KeyedService.AnyKeywhich has changed behavior in .NET 10.GetKeyedService(AnyKey)now throwsInvalidOperationExceptionandGetKeyedServices(AnyKey)no longer returns AnyKey registrations.
- Find
- OpenRewrite.Recipes.Net10.FindMakeGenericSignatureType
- Find
Type.MakeGenericSignatureTypevalidation change - Finds calls to
Type.MakeGenericSignatureType()which now validates that the first argument is a generic type definition in .NET 10.
- Find
- OpenRewrite.Recipes.Net10.FindQueryableMaxByMinByObsolete
- Find obsolete
Queryable.MaxBy/MinBywithIComparer<TSource>(SYSLIB0061) - Finds
Queryable.MaxByandQueryable.MinByoverloads takingIComparer<TSource>which are obsolete in .NET 10. Use the overloads takingIComparer<TKey>instead.
- Find obsolete
- OpenRewrite.Recipes.Net10.FindRazorRuntimeCompilationObsolete
- Find obsolete
AddRazorRuntimeCompilationcalls (ASPDEPR003) - Finds calls to
AddRazorRuntimeCompilationwhich is obsolete in .NET 10. Use Hot Reload instead for development scenarios.
- Find obsolete
- OpenRewrite.Recipes.Net10.FindRfc2898DeriveBytesObsolete
- Find obsolete
Rfc2898DeriveBytesconstructors (SYSLIB0060) - Finds
new Rfc2898DeriveBytes(...)constructor calls which are obsolete in .NET 10. Use the staticRfc2898DeriveBytes.Pbkdf2()method instead.
- Find obsolete
- OpenRewrite.Recipes.Net10.FindSslAuthEnumTypes
- Find obsolete SSL authentication enum types
- Finds usage of
ExchangeAlgorithmType,CipherAlgorithmType, andHashAlgorithmTypefromSystem.Security.Authentication. These enum types are obsolete in .NET 10 (SYSLIB0058). UseSslStream.NegotiatedCipherSuiteinstead.
- OpenRewrite.Recipes.Net10.FindSslStreamObsoleteProperties
- Find obsolete
SslStreamcipher properties (SYSLIB0058) - Finds usages of
SslStream.KeyExchangeAlgorithm,KeyExchangeStrength,CipherAlgorithm,CipherStrength,HashAlgorithm, andHashStrengthwhich are obsolete in .NET 10. UseSslStream.NegotiatedCipherSuiteinstead.
- Find obsolete
- OpenRewrite.Recipes.Net10.FindSystemDrawingExceptionChange
- Find
catch (OutOfMemoryException)that may needExternalException - In .NET 10, System.Drawing GDI+ errors now throw
ExternalExceptioninstead ofOutOfMemoryException. This recipe finds catch blocks that catchOutOfMemoryExceptionwhich may need to also catchExternalException.
- Find
- OpenRewrite.Recipes.Net10.FindSystemEventsThreadShutdownObsolete
- Find obsolete
SystemEvents.EventsThreadShutdown(SYSLIB0059) - Finds usages of
SystemEvents.EventsThreadShutdownwhich is obsolete in .NET 10. UseAppDomain.ProcessExitinstead.
- Find obsolete
- OpenRewrite.Recipes.Net10.FindWebHostBuilderObsolete
- Find obsolete
WebHostBuilder/IWebHost/WebHostusage (ASPDEPR004/ASPDEPR008) - Finds usages of
WebHostBuilder,IWebHost, andWebHostwhich are obsolete in .NET 10. Migrate toHostBuilderorWebApplicationBuilderinstead.
- Find obsolete
- OpenRewrite.Recipes.Net10.FindWinFormsObsoleteApis
- Find obsolete Windows Forms APIs (WFDEV004/005/006)
- Finds usages of Windows Forms APIs that are obsolete in .NET 10, including
Form.OnClosing/OnClosed(WFDEV004),Clipboard.GetData(WFDEV005), and legacy controls likeContextMenu,DataGrid,MainMenu(WFDEV006).
- OpenRewrite.Recipes.Net10.FindWithOpenApiDeprecated
- Find deprecated
WithOpenApicalls (ASPDEPR002) - Finds calls to
.WithOpenApi()which is deprecated in .NET 10. Remove the call or useAddOpenApiOperationTransformerinstead.
- Find deprecated
- OpenRewrite.Recipes.Net10.FindX500DistinguishedNameValidation
- Find
X500DistinguishedNamestring constructor stricter validation - Finds
new X500DistinguishedName(string, ...)constructor calls which have stricter validation in .NET 10. Non-Windows environments may reject previously accepted values.
- Find
- OpenRewrite.Recipes.Net10.FindXsltSettingsEnableScriptObsolete
- Find obsolete
XsltSettings.EnableScript(SYSLIB0062) - Finds usages of
XsltSettings.EnableScriptwhich is obsolete in .NET 10.
- Find obsolete
- OpenRewrite.Recipes.Net10.FormOnClosingRename
- Rename
Form.OnClosing/OnClosedtoOnFormClosing/OnFormClosed(WFDEV004) - Renames
Form.OnClosingtoOnFormClosingandForm.OnClosedtoOnFormClosedfor .NET 10 compatibility. Parameter type changes (CancelEventArgs→FormClosingEventArgs,EventArgs→FormClosedEventArgs) must be updated manually.
- Rename
- OpenRewrite.Recipes.Net10.InsertAdjacentElementOrientParameterRename
- Rename
orientparameter toorientationinHtmlElement.InsertAdjacentElement - The
orientparameter ofHtmlElement.InsertAdjacentElementwas renamed toorientationin .NET 10. This recipe updates named arguments in method calls to use the new parameter name.
- Rename
- OpenRewrite.Recipes.Net10.KnownNetworksRename
- Rename
KnownNetworkstoKnownIPNetworks(ASPDEPR005) - Renames
ForwardedHeadersOptions.KnownNetworkstoKnownIPNetworksfor .NET 10 compatibility.
- Rename
- OpenRewrite.Recipes.Net10.MlDsaSlhDsaSecretKeyToPrivateKey
- Rename MLDsa/SlhDsa
SecretKeymembers toPrivateKey - Renames
SecretKeytoPrivateKeyin MLDsa and SlhDsa post-quantum cryptography APIs to align with .NET 10 naming conventions.
- Rename MLDsa/SlhDsa
- OpenRewrite.Recipes.Net10.RazorRuntimeCompilationObsolete
- Remove obsolete
AddRazorRuntimeCompilationcalls (ASPDEPR003) - Removes
AddRazorRuntimeCompilation()calls which are obsolete in .NET 10. Use Hot Reload instead for development scenarios.
- Remove obsolete
- OpenRewrite.Recipes.Net10.UpgradeToDotNet10
- Migrate to .NET 10
- Migrate C# projects to .NET 10, applying necessary API changes. Includes all .NET 9 (and earlier) migration steps. See https://learn.microsoft.com/en-us/dotnet/core/compatibility/10.0.
- OpenRewrite.Recipes.Net10.WithOpenApiDeprecated
- Remove deprecated
WithOpenApicalls (ASPDEPR002) - Removes
.WithOpenApi()calls which are deprecated in .NET 10. The call is removed from fluent method chains.
- Remove deprecated
- OpenRewrite.Recipes.Net3_0.FindCompactOnMemoryPressure
- Find
CompactOnMemoryPressureusage (removed in ASP.NET Core 3.0) - Finds usages of
CompactOnMemoryPressurewhich was removed fromMemoryCacheOptionsin ASP.NET Core 3.0.
- Find
- OpenRewrite.Recipes.Net3_0.FindConnectionAdapter
- Find
IConnectionAdapterusage (removed in ASP.NET Core 3.0) - Finds usages of
IConnectionAdapterwhich was removed from Kestrel in ASP.NET Core 3.0. Use Connection Middleware instead.
- Find
- OpenRewrite.Recipes.Net3_0.FindHttpContextAuthentication
- Find
HttpContext.Authenticationusage (removed in ASP.NET Core 3.0) - Finds usages of
HttpContext.Authenticationwhich was removed in ASP.NET Core 3.0. Use dependency injection to getIAuthenticationServiceinstead.
- Find
- OpenRewrite.Recipes.Net3_0.FindNewtonsoftJson
- Find Newtonsoft.Json usage
- Finds usages of Newtonsoft.Json types (
JObject,JArray,JToken,JsonConvert) that should be migrated toSystem.Text.Jsonor explicitly preserved viaMicrosoft.AspNetCore.Mvc.NewtonsoftJsonin ASP.NET Core 3.0+.
- OpenRewrite.Recipes.Net3_0.FindObsoleteLocalizationApis
- Find obsolete localization APIs (ASP.NET Core 3.0)
- Finds usages of
ResourceManagerWithCultureStringLocalizerandWithCulture()which are obsolete in ASP.NET Core 3.0.
- OpenRewrite.Recipes.Net3_0.FindSpaServices
- Find SpaServices/NodeServices usage (obsolete in ASP.NET Core 3.0)
- Finds usages of
SpaServicesandNodeServiceswhich are obsolete in ASP.NET Core 3.0.
- OpenRewrite.Recipes.Net3_0.FindSynchronousIO
- Find synchronous IO usage (disabled in ASP.NET Core 3.0)
- Finds references to
AllowSynchronousIOwhich indicates synchronous IO usage that is disabled by default in ASP.NET Core 3.0.
- OpenRewrite.Recipes.Net3_0.FindUseMvc
- Find
UseMvc/AddMvcusage (replaced in ASP.NET Core 3.0) - Finds usages of
app.UseMvc(),app.UseMvcWithDefaultRoute(), andservices.AddMvc()which should be migrated to endpoint routing and more specific service registration in ASP.NET Core 3.0.
- Find
- OpenRewrite.Recipes.Net3_0.FindWebApiCompatShim
- Find Web API compatibility shim usage (removed in ASP.NET Core 3.0)
- Finds usages of
ApiController,HttpResponseMessage, and other types fromMicrosoft.AspNetCore.Mvc.WebApiCompatShimwhich was removed in ASP.NET Core 3.0.
- OpenRewrite.Recipes.Net3_0.FindWebHostBuilder
- Find
WebHostBuilder/WebHost.CreateDefaultBuilderusage (replaced in ASP.NET Core 3.0) - Finds usages of
WebHost.CreateDefaultBuilder()andnew WebHostBuilder()which should be migrated toHost.CreateDefaultBuilder()withConfigureWebHostDefaults()in ASP.NET Core 3.0.
- Find
- OpenRewrite.Recipes.Net3_0.UpgradeToDotNet3_0
- Migrate to .NET Core 3.0
- Migrate C# projects from .NET Core 2.x to .NET Core 3.0, applying necessary API changes for removed and replaced types. See https://learn.microsoft.com/en-us/dotnet/core/compatibility/3.0.
- OpenRewrite.Recipes.Net3_0.UseApiControllerBase
- Migrate ApiController to ControllerBase
- Replace
ApiControllerbase class (from the removed WebApiCompatShim) withControllerBaseand add the[ApiController]attribute. The shim was removed in ASP.NET Core 3.0.
- OpenRewrite.Recipes.Net3_1.FindSameSiteNone
- Find
SameSiteMode.Noneusage (behavior changed in .NET Core 3.1) - Finds usages of
SameSiteMode.Nonewhich changed behavior in .NET Core 3.1 due to Chrome 80 SameSite cookie changes. Apps using remote authentication may need browser sniffing.
- Find
- OpenRewrite.Recipes.Net3_1.UpgradeToDotNet3_1
- Migrate to .NET Core 3.1
- Migrate C# projects from .NET Core 3.0 to .NET Core 3.1. Includes all .NET Core 3.0 migration steps. See https://learn.microsoft.com/en-us/dotnet/core/compatibility/3.1.
- OpenRewrite.Recipes.Net5.FindCodeAccessSecurity
- Find Code Access Security usage (obsolete in .NET 5)
- Finds usages of Code Access Security types (
SecurityPermission,PermissionSet, etc.) which are obsolete in .NET 5+.
- OpenRewrite.Recipes.Net5.FindPrincipalPermissionAttribute
- Find
PrincipalPermissionAttributeusage (SYSLIB0003) - Finds usages of
PrincipalPermissionAttributewhich is obsolete in .NET 5+ (SYSLIB0003) and throwsNotSupportedExceptionat runtime.
- Find
- OpenRewrite.Recipes.Net5.FindUtf7Encoding
- Find
Encoding.UTF7usage (SYSLIB0001) - Finds usages of
Encoding.UTF7andUTF7Encodingwhich are obsolete in .NET 5+ (SYSLIB0001). UTF-7 is insecure.
- Find
- OpenRewrite.Recipes.Net5.FindWinHttpHandler
- Find
WinHttpHandlerusage (removed in .NET 5) - Finds usages of
WinHttpHandlerwhich was removed from the .NET 5 runtime. Install theSystem.Net.Http.WinHttpHandlerNuGet package explicitly.
- Find
- OpenRewrite.Recipes.Net5.FindWinRTInterop
- Find WinRT interop usage (removed in .NET 5)
- Finds usages of WinRT interop types (
WindowsRuntimeType,WindowsRuntimeMarshal, etc.) which were removed in .NET 5.
- OpenRewrite.Recipes.Net5.UpgradeToDotNet5
- Migrate to .NET 5
- Migrate C# projects from .NET Core 3.1 to .NET 5.0. Includes all .NET Core 3.0 and 3.1 migration steps. See https://learn.microsoft.com/en-us/dotnet/core/compatibility/5.0.
- OpenRewrite.Recipes.Net6.FindAssemblyCodeBase
- Find
Assembly.CodeBase/EscapedCodeBaseusage (SYSLIB0012) - Finds usages of
Assembly.CodeBaseandAssembly.EscapedCodeBasewhich are obsolete (SYSLIB0012). UseAssembly.Locationinstead.
- Find
- OpenRewrite.Recipes.Net6.FindIgnoreNullValues
- Find
JsonSerializerOptions.IgnoreNullValuesusage (SYSLIB0020) - Finds usages of
JsonSerializerOptions.IgnoreNullValueswhich is obsolete in .NET 6 (SYSLIB0020). UseDefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNullinstead.
- Find
- OpenRewrite.Recipes.Net6.FindThreadAbort
- Find
Thread.Abortusage (SYSLIB0006) - Finds calls to
Thread.Abort()which throwsPlatformNotSupportedExceptionin .NET 6+ (SYSLIB0006). UseCancellationTokenfor cooperative cancellation instead.
- Find
- OpenRewrite.Recipes.Net6.FindWebRequest
- Find
WebRequest/HttpWebRequest/WebClientusage (SYSLIB0014) - Finds usages of
WebRequest,HttpWebRequest, andWebClientwhich are obsolete in .NET 6 (SYSLIB0014). UseHttpClientinstead.
- Find
- OpenRewrite.Recipes.Net6.FindX509PrivateKey
- Find
X509Certificate2.PrivateKeyusage (SYSLIB0028) - Finds usages of
X509Certificate2.PrivateKeywhich is obsolete (SYSLIB0028). UseGetRSAPrivateKey(),GetECDsaPrivateKey(), or the appropriate algorithm-specific method instead.
- Find
- OpenRewrite.Recipes.Net6.UpgradeToDotNet6
- Migrate to .NET 6
- Migrate C# projects to .NET 6, applying necessary API changes for obsoleted cryptographic types and other breaking changes. Includes all .NET Core 3.0, 3.1, and .NET 5 migration steps. See https://learn.microsoft.com/en-us/dotnet/core/compatibility/6.0.
- OpenRewrite.Recipes.Net6.UseEnvironmentCurrentManagedThreadId
- Use Environment.CurrentManagedThreadId
- Replace
Thread.CurrentThread.ManagedThreadIdwithEnvironment.CurrentManagedThreadId(CA1840). Available since .NET 6.
- OpenRewrite.Recipes.Net6.UseEnvironmentProcessId
- Use Environment.ProcessId
- Replace
Process.GetCurrentProcess().IdwithEnvironment.ProcessId(CA1837). Available since .NET 6.
- OpenRewrite.Recipes.Net6.UseEnvironmentProcessPath
- Use Environment.ProcessPath
- Replace
Process.GetCurrentProcess().MainModule.FileNamewithEnvironment.ProcessPath(CA1839). Available since .NET 6.
- OpenRewrite.Recipes.Net6.UseLinqDistinctBy
- Use LINQ DistinctBy()
- Replace
collection.GroupBy(selector).Select(g => g.First())withcollection.DistinctBy(selector). Available since .NET 6.
- OpenRewrite.Recipes.Net6.UseLinqMaxMinBy
- Use LINQ MaxBy() and MinBy()
- Replace
collection.OrderByDescending(selector).First()withcollection.MaxBy(selector)andcollection.OrderBy(selector).First()withcollection.MinBy(selector). Also handles.Last()variants (OrderBy().Last() → MaxBy, OrderByDescending().Last() → MinBy). Note: MinBy/MaxBy return default for empty reference-type sequences instead of throwing. Available since .NET 6.
- OpenRewrite.Recipes.Net6.UseRandomShared
- Use Random.Shared
- Replace
new Random().Method(...)withRandom.Shared.Method(...). Available since .NET 6.
- OpenRewrite.Recipes.Net6.UseStringContainsChar
- Use string.Contains(char) overload
- Finds calls to
string.Contains("x")with a single-character string literal that could use thestring.Contains('x')overload for better performance.
- OpenRewrite.Recipes.Net6.UseStringStartsEndsWithChar
- Use string.StartsWith(char)/EndsWith(char) overload
- Finds calls to
string.StartsWith("x")andstring.EndsWith("x")with a single-character string literal that could use the char overload for better performance.
- OpenRewrite.Recipes.Net6.UseThrowIfNull
- Use ArgumentNullException.ThrowIfNull()
- Replace
if (x == null) throw new ArgumentNullException(nameof(x))guard clauses withArgumentNullException.ThrowIfNull(x)(CA1510). Handles== null,is null, reversednull ==, string literal param names, and braced then-blocks. Available since .NET 6.
- OpenRewrite.Recipes.Net7.FindObsoleteSslProtocols
- Find obsolete
SslProtocols.Tls/Tls11usage (SYSLIB0039) - Finds usages of
SslProtocols.TlsandSslProtocols.Tls11which are obsolete in .NET 7 (SYSLIB0039). UseSslProtocols.Tls12,SslProtocols.Tls13, orSslProtocols.Noneinstead.
- Find obsolete
- OpenRewrite.Recipes.Net7.FindRfc2898InsecureCtors
- Find insecure
Rfc2898DeriveBytesconstructors (SYSLIB0041) - Finds
Rfc2898DeriveBytesconstructor calls that use default SHA1 or low iteration counts, which are obsolete in .NET 7 (SYSLIB0041). SpecifyHashAlgorithmNameand at least 600,000 iterations.
- Find insecure
- OpenRewrite.Recipes.Net7.UpgradeToDotNet7
- Migrate to .NET 7
- Migrate C# projects to .NET 7, applying necessary API changes. See https://learn.microsoft.com/en-us/dotnet/core/compatibility/7.0.
- OpenRewrite.Recipes.Net7.UseLinqOrder
- Use LINQ Order() and OrderDescending()
- Replace
collection.OrderBy(x => x)withcollection.Order()andcollection.OrderByDescending(x => x)withcollection.OrderDescending(). Available since .NET 7.
- OpenRewrite.Recipes.Net7.UseThrowIfNegative
- Use ArgumentOutOfRangeException.ThrowIfNegative()
- Replace
if (value < 0) throw new ArgumentOutOfRangeException(nameof(value))guard clauses withArgumentOutOfRangeException.ThrowIfNegative(value). Also handles reversed0 > value. Available since .NET 7.
- OpenRewrite.Recipes.Net7.UseThrowIfNegativeOrZero
- Use ArgumentOutOfRangeException.ThrowIfNegativeOrZero()
- Replace
if (value <= 0) throw new ArgumentOutOfRangeException(nameof(value))guard clauses withArgumentOutOfRangeException.ThrowIfNegativeOrZero(value). Also handles reversed0 >= value. Available since .NET 7.
- OpenRewrite.Recipes.Net7.UseThrowIfNullOrEmpty
- Use ArgumentException.ThrowIfNullOrEmpty()
- Replace
if (string.IsNullOrEmpty(s)) throw new ArgumentException("...", nameof(s))guard clauses withArgumentException.ThrowIfNullOrEmpty(s). Available since .NET 7.
- OpenRewrite.Recipes.Net8.FindAddContext
- Find
JsonSerializerOptions.AddContextusage (SYSLIB0049) - Finds calls to
JsonSerializerOptions.AddContext<T>()which is obsolete in .NET 8 (SYSLIB0049). UseTypeInfoResolverChainorTypeInfoResolverinstead.
- Find
- OpenRewrite.Recipes.Net8.FindAesGcmOldConstructor
- Find
AesGcmconstructor without tag size (SYSLIB0053) - Finds
new AesGcm(key)constructor calls without an explicit tag size parameter. In .NET 8, the single-argument constructor is obsolete (SYSLIB0053). Usenew AesGcm(key, tagSizeInBytes)instead.
- Find
- OpenRewrite.Recipes.Net8.FindFormatterBasedSerialization
- Find formatter-based serialization types (SYSLIB0050/0051)
- Finds usage of formatter-based serialization types (
FormatterConverter,IFormatter,ObjectIDGenerator,ObjectManager,SurrogateSelector,SerializationInfo,StreamingContext). These are obsolete in .NET 8 (SYSLIB0050/0051).
- OpenRewrite.Recipes.Net8.FindFrozenCollection
- Find ToImmutable() that could use Frozen collections*
- Finds usages of
ToImmutableDictionary()andToImmutableHashSet(). In .NET 8+,ToFrozenDictionary()andToFrozenSet()provide better read performance.
- OpenRewrite.Recipes.Net8.FindRegexCompileToAssembly
- Find
Regex.CompileToAssemblyusage (SYSLIB0052) - Finds usage of
Regex.CompileToAssembly()andRegexCompilationInfo. These are obsolete in .NET 8 (SYSLIB0052). Use the Regex source generator instead.
- Find
- OpenRewrite.Recipes.Net8.FindSerializationConstructors
- Find legacy serialization constructors (SYSLIB0051)
- Finds legacy serialization constructors
.ctor(SerializationInfo, StreamingContext)which are obsolete in .NET 8 (SYSLIB0051). TheISerializablepattern is no longer recommended.
- OpenRewrite.Recipes.Net8.FindTimeAbstraction
- Find DateTime.Now/UtcNow usage (TimeProvider in .NET 8)
- Finds usages of
DateTime.Now,DateTime.UtcNow,DateTimeOffset.Now, andDateTimeOffset.UtcNow. In .NET 8+,TimeProvideris the recommended abstraction for time.
- OpenRewrite.Recipes.Net8.UpgradeToDotNet8
- Migrate to .NET 8
- Migrate C# projects to .NET 8, applying necessary API changes. Includes all .NET 7 migration steps. See https://learn.microsoft.com/en-us/dotnet/core/compatibility/8.0.
- OpenRewrite.Recipes.Net8.UseThrowIfGreaterThan
- Use ArgumentOutOfRangeException.ThrowIfGreaterThan()
- Replace
if (value > other) throw new ArgumentOutOfRangeException(nameof(value))guard clauses withArgumentOutOfRangeException.ThrowIfGreaterThan(value, other). Also handles reversedother < valueand>=/ThrowIfGreaterThanOrEqual. Available since .NET 8.
- OpenRewrite.Recipes.Net8.UseThrowIfLessThan
- Use ArgumentOutOfRangeException.ThrowIfLessThan()
- Replace
if (value < other) throw new ArgumentOutOfRangeException(nameof(value))guard clauses withArgumentOutOfRangeException.ThrowIfLessThan(value, other). Also handles reversedother > valueand<=/ThrowIfLessThanOrEqual. Available since .NET 8.
- OpenRewrite.Recipes.Net8.UseThrowIfNullOrWhiteSpace
- Use ArgumentException.ThrowIfNullOrWhiteSpace()
- Replace
if (string.IsNullOrWhiteSpace(s)) throw new ArgumentException("...", nameof(s))guard clauses withArgumentException.ThrowIfNullOrWhiteSpace(s). Available since .NET 8.
- OpenRewrite.Recipes.Net8.UseThrowIfZero
- Use ArgumentOutOfRangeException.ThrowIfZero()
- Replace
if (value == 0) throw new ArgumentOutOfRangeException(nameof(value))guard clauses withArgumentOutOfRangeException.ThrowIfZero(value). Also handles reversed0 == value. Available since .NET 8.
- OpenRewrite.Recipes.Net8.UseTimeProvider
- Use TimeProvider instead of DateTime/DateTimeOffset static properties
- Replace
DateTime.UtcNow,DateTime.Now,DateTimeOffset.UtcNow, andDateTimeOffset.NowwithTimeProvider.System.GetUtcNow()/GetLocalNow()equivalents. TimeProvider enables testability and consistent time sources. Available since .NET 8.
- OpenRewrite.Recipes.Net9.FindAuthenticationManager
- Find
AuthenticationManagerusage (SYSLIB0009) - Finds usages of
AuthenticationManagerwhich is not supported in .NET 9 (SYSLIB0009). Methods will no-op or throwPlatformNotSupportedException.
- Find
- OpenRewrite.Recipes.Net9.FindBinaryFormatter
- Find
BinaryFormatterusage (removed in .NET 9) - Finds usages of
BinaryFormatterwhich always throwsNotSupportedExceptionin .NET 9. Migrate to a different serializer such asSystem.Text.Json,XmlSerializer, orDataContractSerializer.
- Find
- OpenRewrite.Recipes.Net9.FindBinaryReaderReadString
- Find
BinaryReader.ReadStringbehavior change - Finds calls to
BinaryReader.ReadString()which now returns the Unicode replacement character (\uFFFD) for malformed UTF-8 byte sequences in .NET 9, instead of the previous behavior. Verify your code handles the replacement character correctly.
- Find
- OpenRewrite.Recipes.Net9.FindDistributedCache
- Find IDistributedCache usage (HybridCache in .NET 9)
- Finds usages of
IDistributedCache. In .NET 9,HybridCacheis the recommended replacement with L1/L2 caching, stampede protection, and tag-based invalidation.
- OpenRewrite.Recipes.Net9.FindEnumConverter
- Find
EnumConverterconstructor validation change - Finds
new EnumConverter()constructor calls. In .NET 9,EnumConvertervalidates that the registered type is actually an enum and throwsArgumentExceptionif not.
- Find
- OpenRewrite.Recipes.Net9.FindExecuteUpdateSync
- Find synchronous ExecuteUpdate/ExecuteDelete (EF Core 9)
- Finds usages of synchronous
ExecuteUpdate()andExecuteDelete()which were removed in EF Core 9. UseExecuteUpdateAsync/ExecuteDeleteAsyncinstead.
- OpenRewrite.Recipes.Net9.FindHttpClientHandlerCast
- Find
HttpClientHandlerusage (HttpClientFactory default change) - Finds usages of
HttpClientHandlerwhich may break whenHttpClientFactoryswitches its default handler toSocketsHttpHandlerin .NET 9.
- Find
- OpenRewrite.Recipes.Net9.FindHttpListenerRequestUserAgent
- Find
HttpListenerRequest.UserAgentnullable change - Finds accesses to
HttpListenerRequest.UserAgentwhich changed fromstringtostring?in .NET 9. Code that assumesUserAgentis non-null may throwNullReferenceException.
- Find
- OpenRewrite.Recipes.Net9.FindImplicitAuthenticationDefault
- Find implicit authentication default scheme (ASP.NET Core 9)
- Finds calls to
AddAuthentication()with no arguments. In .NET 9, a single registered authentication scheme is no longer automatically used as the default.
- OpenRewrite.Recipes.Net9.FindInMemoryDirectoryInfo
- Find
InMemoryDirectoryInforootDir prepend change - Finds
new InMemoryDirectoryInfo()constructor calls. In .NET 9,rootDiris prepended to file paths that don't start with therootDir, which may change file matching behavior.
- Find
- OpenRewrite.Recipes.Net9.FindIncrementingPollingCounter
- Find
IncrementingPollingCounterasync callback change - Finds
new IncrementingPollingCounter()constructor calls. In .NET 9, the initial callback invocation is asynchronous instead of synchronous, which may change timing behavior.
- Find
- OpenRewrite.Recipes.Net9.FindJsonDocumentNullable
- Find
JsonSerializer.DeserializenullableJsonDocumentchange - Finds
JsonSerializer.Deserialize()calls. In .NET 9, nullableJsonDocumentproperties now deserialize to aJsonDocumentwithRootElement.ValueKind == JsonValueKind.Nullinstead of beingnull.
- Find
- OpenRewrite.Recipes.Net9.FindJsonStringEnumConverter
- Find non-generic JsonStringEnumConverter
- Finds usages of the non-generic
JsonStringEnumConverter. In .NET 9, the genericJsonStringEnumConverter<TEnum>is preferred for AOT compatibility.
- OpenRewrite.Recipes.Net9.FindRuntimeHelpersGetSubArray
- Find
RuntimeHelpers.GetSubArrayreturn type change - Finds calls to
RuntimeHelpers.GetSubArray()which may return a different array type in .NET 9. Code that depends on the runtime type of the returned array may break.
- Find
- OpenRewrite.Recipes.Net9.FindSafeEvpPKeyHandleDuplicate
- Find
SafeEvpPKeyHandle.DuplicateHandleup-ref change - Finds calls to
SafeEvpPKeyHandle.DuplicateHandle(). In .NET 9, this method now increments the reference count instead of creating a deep copy, which may affect handle lifetime.
- Find
- OpenRewrite.Recipes.Net9.FindServicePointManager
- Find
ServicePointManagerusage (SYSLIB0014) - Finds usages of
ServicePointManagerwhich is fully obsolete in .NET 9 (SYSLIB0014). Settings onServicePointManagerdon't affectSslStreamorHttpClient.
- Find
- OpenRewrite.Recipes.Net9.FindSwashbuckle
- Find Swashbuckle usage (ASP.NET Core 9 built-in OpenAPI)
- Finds usages of Swashbuckle APIs (
AddSwaggerGen,UseSwagger,UseSwaggerUI). .NET 9 includes built-in OpenAPI support. Consider migrating toAddOpenApi()/MapOpenApi().
- OpenRewrite.Recipes.Net9.FindX509CertificateConstructors
- Find obsolete
X509Certificate2/X509Certificateconstructors (SYSLIB0057) - Finds usages of
X509Certificate2andX509Certificateconstructors that accept binary content or file paths, which are obsolete in .NET 9 (SYSLIB0057). UseX509CertificateLoadermethods instead.
- Find obsolete
- OpenRewrite.Recipes.Net9.FindZipArchiveCompressionLevel
- Find
ZipArchive.CreateEntrywithCompressionLevel(bit flag change) - Finds
ZipArchive.CreateEntry()andZipFileExtensions.CreateEntryFromFile()calls with aCompressionLevelparameter. In .NET 9, theCompressionLevelvalue now sets general-purpose bit flags in the ZIP central directory header, which may affect interoperability.
- Find
- OpenRewrite.Recipes.Net9.FindZipArchiveEntryEncoding
- Find
ZipArchiveEntryname/comment UTF-8 encoding change - Finds access to
ZipArchiveEntry.Name,FullName, orCommentproperties. In .NET 9, these now respect the UTF-8 flag in ZIP entries, which may change decoded values.
- Find
- OpenRewrite.Recipes.Net9.MigrateSwashbuckleToOpenApi
- Migrate Swashbuckle to built-in OpenAPI
- Migrate from Swashbuckle to the built-in OpenAPI support in ASP.NET Core 9. Replaces
AddSwaggerGen()withAddOpenApi(),UseSwaggerUI()withMapOpenApi(), removesUseSwagger(), removes Swashbuckle packages, and addsMicrosoft.AspNetCore.OpenApi.
- OpenRewrite.Recipes.Net9.RemoveConfigureAwaitFalse
- Remove ConfigureAwait(false)
- Remove
.ConfigureAwait(false)calls that are unnecessary in ASP.NET Core and modern .NET applications (no SynchronizationContext). Do not apply to library code targeting .NET Framework.
- OpenRewrite.Recipes.Net9.UpgradeToDotNet9
- Migrate to .NET 9
- Migrate C# projects to .NET 9, applying necessary API changes. Includes all .NET 7 and .NET 8 migration steps. See https://learn.microsoft.com/en-us/dotnet/core/compatibility/9.0.
- OpenRewrite.Recipes.Net9.UseEscapeSequenceE
- Use \e escape sequence
- Replace
\u001band\x1bescape sequences with\e. C# 13 introduced\eas a dedicated escape sequence for the escape character (U+001B).
- OpenRewrite.Recipes.Net9.UseFrozenCollections
- Use Frozen collections instead of Immutable
- Replace
ToImmutableDictionary()withToFrozenDictionary()andToImmutableHashSet()withToFrozenSet(). Frozen collections (.NET 8+) provide better read performance for collections populated once and read many times.
- OpenRewrite.Recipes.Net9.UseGuidCreateVersion7
- Use Guid.CreateVersion7()
- Replace
Guid.NewGuid()withGuid.CreateVersion7(). Version 7 GUIDs are time-ordered and better for database primary keys, indexing, and sorting. Available since .NET 9.
- OpenRewrite.Recipes.Net9.UseLinqAggregateBy
- Use LINQ AggregateBy()
- Replace
collection.GroupBy(keySelector).ToDictionary(g => g.Key, g => g.Aggregate(seed, func))withcollection.AggregateBy(keySelector, seed, func).ToDictionary(). Available since .NET 9.
- OpenRewrite.Recipes.Net9.UseLinqCountBy
- Use LINQ CountBy()
- Replace
collection.GroupBy(selector).Select(g => g.Count())withcollection.CountBy(selector). Available since .NET 9.
- OpenRewrite.Recipes.Net9.UseLinqIndex
- Use LINQ Index()
- Replace
collection.Select((item, index) => (index, item))withcollection.Index(). Available since .NET 9.
- OpenRewrite.Recipes.Net9.UseLockObject
- Use System.Threading.Lock for lock fields
- Replace
objectfields initialized withnew object()withSystem.Threading.Lockinitialized withnew(). The Lock type provides better performance with the lock statement. Available since .NET 9.
- OpenRewrite.Recipes.Net9.UseMapStaticAssets
- Use MapStaticAssets()
- Replace
UseStaticFiles()withMapStaticAssets()for ASP.NET Core 9. Only applies when the receiver supportsIEndpointRouteBuilder(WebApplication / minimal hosting). Skips Startup.cs patterns usingIApplicationBuilderwhereMapStaticAssetsis not available.
- OpenRewrite.Recipes.Net9.UseTaskCompletedTask
- Use Task.CompletedTask
- Replace
Task.FromResult(0),Task.FromResult(true), andTask.FromResult(false)withTask.CompletedTaskwhen the return type isTask(notTask<T>).
- OpenRewrite.Recipes.Net9.UseVolatileReadWrite
- Use Volatile.Read/Write (SYSLIB0054)
- Replace
Thread.VolatileReadandThread.VolatileWritewithVolatile.ReadandVolatile.Write. The Thread methods are obsolete in .NET 9 (SYSLIB0054).
- OpenRewrite.Recipes.Net9.UseX509CertificateLoader
- Use X509CertificateLoader (SYSLIB0057)
- Replace
new X509Certificate2(path, password)withX509CertificateLoader.LoadPkcs12FromFile(path, password). The two-argument X509Certificate2 constructor is obsolete in .NET 9 (SYSLIB0057).
- OpenRewrite.Recipes.RemoveNuGetPackageReference
- Remove NuGet package reference
- Removes a
<PackageReference>from .csproj files.
- OpenRewrite.Recipes.UpgradeNuGetPackageVersion
- Upgrade NuGet package version
- Upgrades the version of a NuGet
<PackageReference>or<PackageVersion>in .csproj and Directory.Packages.props files.
recipes-tunit
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.AsyncLifetimeToBeforeAfterTest
- Find
IAsyncLifetimeneeding TUnit migration - Find classes implementing
IAsyncLifetimethat should use[Before(Test)]and[After(Test)]for TUnit.
- Find
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.ChangeXUnitUsings
- Change xUnit using directives to TUnit
- Replace
using Xunit;withusing TUnit.Core;andusing TUnit.Assertions;, and removeusing Xunit.Abstractions;andusing Xunit.Sdk;.
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.ClassFixtureToClassDataSource
- Find
IClassFixture<T>needing TUnit migration - Find classes implementing
IClassFixture<T>that should use[ClassDataSource<T>]for TUnit.
- Find
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.CollectionToNotInParallel
- Replace
[Collection]with[NotInParallel] - Replace the xUnit
[Collection("name")]attribute with the TUnit[NotInParallel("name")]attribute.
- Replace
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.ConstructorToBeforeTest
- Find test constructors needing
[Before(Test)] - Find constructors in test classes that should be converted to
[Before(Test)]methods for TUnit.
- Find test constructors needing
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.DisposableToAfterTest
- Replace
IDisposablewith[After(Test)] - Remove
IDisposablefrom the base type list and add[After(Test)]to theDispose()method.
- Replace
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.FactSkipToSkipAttribute
- Extract
Skipinto[Skip]attribute - Extract the
Skipargument from[Fact(Skip = "...")]or[Theory(Skip = "...")]into a separate TUnit[Skip("...")]attribute.
- Extract
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.FactTimeoutToTimeoutAttribute
- Extract
Timeoutinto[Timeout]attribute - Extract the
Timeoutargument from[Fact(Timeout = ...)]or[Theory(Timeout = ...)]into a separate TUnit[Timeout(...)]attribute.
- Extract
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.FactToTest
- Replace
[Fact]with[Test] - Replace the xUnit
[Fact]attribute with the TUnit[Test]attribute.
- Replace
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.InlineDataToArguments
- Replace
[InlineData]with[Arguments] - Replace the xUnit
[InlineData]attribute with the TUnit[Arguments]attribute.
- Replace
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.MemberDataToMethodDataSource
- Replace
[MemberData]with[MethodDataSource] - Replace the xUnit
[MemberData]attribute with the TUnit[MethodDataSource]attribute. Fields and properties referenced by MemberData are converted to methods.
- Replace
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.MigrateFromXUnit
- Migrate from xUnit to TUnit
- Migrate xUnit test attributes, assertions, and lifecycle patterns to their TUnit equivalents.
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.MigrateFromXUnitAttributes
- Migrate xUnit attributes to TUnit
- Replace xUnit test attributes ([Fact], [Theory], [InlineData], etc.) with their TUnit equivalents.
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.MigrateXUnitAssertions
- Migrate xUnit assertions to TUnit
- Replace xUnit
Assert.*calls with TUnit's fluentawait Assert.That(...).Is*()assertions. Note: test methods may need to be changed toasync Taskseparately.
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.MigrateXUnitDependencies
- Migrate xUnit NuGet dependencies to TUnit
- Remove xUnit NuGet package references, add TUnit, and upgrade the target framework to at least .NET 9.
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.TestOutputHelperToTestContext
- Find
ITestOutputHelperneeding TUnit migration - Find usages of xUnit's
ITestOutputHelperthat should be replaced with TUnit'sTestContext.
- Find
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.TheoryToTest
- Replace
[Theory]with[Test] - Replace the xUnit
[Theory]attribute with the TUnit[Test]attribute.
- Replace
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.TraitCategoryToCategory
- Replace
[Trait("Category", ...)]with[Category] - Replace xUnit
[Trait("Category", "X")]with TUnit's dedicated[Category("X")]attribute.
- Replace
- OpenRewrite.Recipes.TUnit.Migration.FromXUnit.TraitToProperty
- Replace
[Trait]with[Property] - Replace the xUnit
[Trait]attribute with the TUnit[Property]attribute.
- Replace
rewrite-ai
- io.moderne.ai.FindAgentsInUse
- Find AI agents configuration files
- Scans codebases to identify usage of AI agents by looking at the agent configuration files present in the repository.
- io.moderne.ai.FindLibrariesInUse
- Find AI libraries in use
- Scans codebases to identify usage of AI services. Detects AI libraries across Java dependencies. Useful for auditing and understanding AI integration patterns.
- io.moderne.ai.FindModelsInUse
- Find AI models in use
- Scans codebases to identify usage of Large Language Models (LLMs). Detects model references and configuration patterns across Java classes, properties files, YAML configs... Useful for identifying model usage.
rewrite-angular
- org.openrewrite.angular.UpgradeToAngular10
- Upgrade to Angular 10
- Migrates Angular 9.x applications to Angular 10. This includes removing the deprecated
es5BrowserSupportoption fromangular.json, renaming deprecatedvalidator/asyncValidatorto their plural forms, renamingbrowserslistto.browserslistrc, migrating to solution-styletsconfig.json, and upgrading Angular, TypeScript, and related dependency versions.
- org.openrewrite.angular.UpgradeToAngular11
- Upgrade to Angular 11
- Migrates Angular 10.x applications to Angular 11. This includes replacing
ViewEncapsulation.NativewithViewEncapsulation.ShadowDom, removing the deprecatedextractCssbuild option fromangular.json, flagging deprecated string-basedloadChildrenandpreserveQueryParamsusage, and upgrading Angular, TypeScript, and related dependency versions.
- org.openrewrite.angular.UpgradeToAngular12
- Upgrade to Angular 12
- Migrates Angular 11.x applications to Angular 12. This includes adding
defaultConfiguration: "production"to build targets inangular.json, replacingnode-sasswithsass(Dart Sass), flagging deprecatedasynctest helper and View Engine APIs, and upgrading Angular, TypeScript, and related dependency versions.
- org.openrewrite.angular.UpgradeToAngular13
- Upgrade to Angular 13
- Migrates Angular 12.x applications to Angular 13. This includes updating
tsconfig.jsontarget toes2017, removing IE11 polyfills, removingdefaultProjectfromangular.json, adding TestBed module teardown, simplifyingComponentFactoryResolverusage, and upgrading Angular, TypeScript, and related dependency versions.
- org.openrewrite.angular.UpgradeToAngular14
- Upgrade to Angular 14
- Migrates Angular 13.x applications to Angular 14. This includes replacing form classes with their
Untyped*equivalents for backward compatibility with typed forms, updating deprecatedinitialNavigationrouter option values, removingaotSummariesfrom TestBed calls, and flaggingpathMatchproperties that may need type narrowing.
- org.openrewrite.angular.UpgradeToAngular15
- Upgrade to Angular 15
- Migrates Angular 14.x applications to Angular 15. This includes removing the
relativeLinkResolutionoption fromRouterModule.forRoot(), removing theenableIvycompiler option fromtsconfig.json, flagging the deprecatedDATE_PIPE_DEFAULT_TIMEZONEtoken andprovidedIn: NgModule/'any'usage, and upgrading Angular, TypeScript, and related dependency versions.
- org.openrewrite.angular.UpgradeToAngular16
- Upgrade to Angular 16
- Migrates Angular 15.x applications to Angular 16. This includes removing
entryComponentsandmoduleIdfrom decorators, replacingRouterLinkWithHrefwithRouterLink, moving theXhrFactoryimport to@angular/common, and flagging removed APIs likeReflectiveInjector,renderModuleFactory, andBrowserTransferStateModule.
- org.openrewrite.angular.UpgradeToAngular17
- Upgrade to Angular 17
- Migrates Angular 16.x applications to Angular 17. This includes updating Angular package versions, replacing legacy deep
zone.jsimports, flagging the removedwithNoDomReuseandsetupTestingRouterAPIs, and upgrading TypeScript andzone.jsdependencies.
- org.openrewrite.angular.UpgradeToAngular18
- Upgrade to Angular 18
- Migrates Angular 17.x applications to Angular 18. This includes replacing the deprecated
asynctest helper withwaitForAsync, migratingHttpClientModuletoprovideHttpClient(), moving Transfer State APIs to@angular/core, and flagging removed platform APIs.
- org.openrewrite.angular.UpgradeToAngular19
- Upgrade to Angular 19
- Migrates Angular 18.x applications to Angular 19. This includes updating Angular package versions, adjusting the standalone default, renaming
ExperimentalPendingTaskstoPendingTasks, moving theApplicationConfigimport to@angular/core, and updatingzone.js.
- org.openrewrite.angular.UpgradeToAngular20
- Upgrade to Angular 20
- Migrates Angular 19.x applications to Angular 20. This includes running the Angular 19 migration first, then updating Angular package versions, renaming experimental APIs promoted to stable, and upgrading TypeScript to 5.8.x.
- org.openrewrite.angular.UpgradeToAngular21
- Upgrade to Angular 21
- Migrates Angular 20.x applications to Angular 21. This includes running the Angular 20 migration first, flagging Karma test runner usage for Vitest migration, deprecated NgClass, zone.js-dependent test helpers, and upgrading TypeScript to 5.9.x.
- org.openrewrite.angular.UpgradeToAngular8
- Upgrade to Angular 8
- Migrates Angular 7.x applications to Angular 8. This includes adding the now-required
static: falseto@ViewChildand@ContentChilddecorators, moving theDOCUMENTimport from@angular/platform-browserto@angular/common, removingrxjs-compatand flagging any remaining RxJS 5-style imports, flagging removed@angular/httpimports, converting deprecated string-basedloadChildrento dynamic imports, and upgrading Angular, TypeScript, and related dependency versions.
- org.openrewrite.angular.UpgradeToAngular9
- Upgrade to Angular 9
- Migrates Angular 8.x applications to Angular 9. This includes removing the now-default
static: falsefrom view query decorators, replacingTestBed.get()withTestBed.inject(), adding generic type parameters toModuleWithProviders, enabling AOT compilation inangular.json, updatingtsconfig.jsonmodule settings for Ivy, flagging removed View Engine APIs (Renderer,RenderComponentType,RootRenderer), and upgrading Angular, TypeScript, and related dependency versions.
- org.openrewrite.angular.migration.add-default-configuration
- Add
defaultConfigurationto build targets - Adds
"defaultConfiguration": "production"to build architect targets inangular.json. Angular 12 changedng buildto produce production bundles by default.
- Add
- org.openrewrite.angular.migration.add-localize-polyfill
- Add
@angular/localize/initpolyfill import - Adds
import '@angular/localize/init'topolyfills.ts. Angular 9 introduced the$localizeruntime API for i18n. Projects using internationalization must import this polyfill or the application will fail at runtime with$localize is not defined. The@angular/localizepackage must also be added as a dependency.
- Add
- org.openrewrite.angular.migration.add-module-with-providers-generic
- Add generic type to
ModuleWithProviders - Adds the required generic type parameter to bare
ModuleWithProvidersreturn types. Angular 10 requiresModuleWithProviders<T>whereTis the NgModule type. The module type is inferred from thengModuleproperty in the return statement.
- Add generic type to
- org.openrewrite.angular.migration.add-static-false-to-view-queries
- Add
static: falseto view queries - Adds
static: falseto@ViewChildand@ContentChilddecorators that don't have thestaticproperty. Angular 8 requires an explicitstaticflag for view query decorators. Usingstatic: falsepreserves the Angular 7 default behavior (queries resolved after change detection).
- Add
- org.openrewrite.angular.migration.add-testbed-teardown
- Add TestBed module teardown
- Adds
\{ teardown: \{ destroyAfterEach: true \} \}as the third argument toTestBed.initTestEnvironment()calls. Angular 13 changed the default teardown behavior, and this ensures explicit opt-in for module teardown after each test.
- org.openrewrite.angular.migration.enable-aot-build
- Enable AOT compilation in
angular.json - Adds
"aot": trueto build options inangular.json. Angular 9 made AOT compilation the default, and projects upgrading from Angular 8 should enable it explicitly.
- Enable AOT compilation in
- org.openrewrite.angular.migration.explicit-standalone-flag
- Make standalone flag explicit
- Adds
standalone: falseto non-standalone Angular components, directives, and pipes, and removes redundantstandalone: truesince it became the default in Angular 19.
- org.openrewrite.angular.migration.migrate-constructor-to-inject
- Migrate constructor injection to
inject() - Converts constructor parameter properties in Angular classes to field declarations using the
inject()function. For example,constructor(private svc: MyService) \{\}becomesprivate svc = inject(MyService);.
- Migrate constructor injection to
- org.openrewrite.angular.migration.migrate-input-to-signal
- Migrate
@Input()to signal-basedinput() - Converts
@Input()decorated properties in Angular classes to signal-basedinput()declarations. For example,@Input() name: stringbecomesname = input<string>(), and@Input(\{ required: true \}) name!: stringbecomesname = input.required<string>().
- Migrate
- org.openrewrite.angular.migration.migrate-output-to-signal
- Migrate
@Output()to signal-basedoutput() - Converts
@Output()decorated properties usingEventEmitterin Angular classes to signal-basedoutput()declarations. For example,@Output() clicked = new EventEmitter<void>()becomesclicked = output<void>().
- Migrate
- org.openrewrite.angular.migration.migrate-query-to-signal
- Migrate query decorators to signal-based functions
- Converts
@ViewChild(),@ViewChildren(),@ContentChild(), and@ContentChildren()decorated properties to signal-based query functions. For example,@ViewChild('ref') el: ElementRefbecomesel = viewChild<ElementRef>('ref').
- org.openrewrite.angular.migration.migrate-to-solution-style-tsconfig
- Migrate to solution-style tsconfig
- Migrates a project to use a solution-style
tsconfig.json. The originaltsconfig.jsoncontent is moved totsconfig.base.json(with project-specific fields removed), andtsconfig.jsonis replaced with a solution-style config that references the project's TypeScript configurations. Other tsconfig files that extend./tsconfig.jsonare updated to extend./tsconfig.base.json.
- org.openrewrite.angular.migration.move-document-import
- Move
DOCUMENTimport to@angular/core - Moves the
DOCUMENTimport from older Angular modules to@angular/core.
- Move
- org.openrewrite.angular.migration.remove-aot-summaries
- Remove
aotSummariesfrom TestBed - Removes the
aotSummariesproperty fromTestBed.configureTestingModule()andTestBed.initTestEnvironment()calls. TheaotSummariesparameter was removed in Angular 14 as it was only needed for the View Engine compiler.
- Remove
- org.openrewrite.angular.migration.remove-browser-module-with-server-transition
- Remove
BrowserModule.withServerTransition - Replaces
BrowserModule.withServerTransition(\{ appId: '...' \})withBrowserModuleand adds\{ provide: APP_ID, useValue: '...' \}to the NgModule providers. ThewithServerTransitionmethod was removed in Angular 19.
- Remove
- org.openrewrite.angular.migration.remove-component-factory-resolver
- Remove
ComponentFactoryResolver - Replaces
resolver.resolveComponentFactory(Component)with justComponentand removes theComponentFactoryResolverimport. Since Ivy,ViewContainerRef.createComponentaccepts the component class directly.ComponentFactoryResolverwas deprecated in Angular 13 and removed in Angular 16.
- Remove
- org.openrewrite.angular.migration.remove-default-project
- Remove
defaultProjectfromangular.json - Removes the deprecated
defaultProjectproperty fromangular.json. ThedefaultProjectoption was deprecated in Angular 13 and the CLI infers the default project from the workspace.
- Remove
- org.openrewrite.angular.migration.remove-empty-ng-on-init
- Remove empty
ngOnInitlifecycle hooks - Removes empty
ngOnInitlifecycle hook methods and OnInit interface from Angular components.
- Remove empty
- org.openrewrite.angular.migration.remove-enable-ivy
- Remove
enableIvycompiler option - Removes the
enableIvyoption fromangularCompilerOptionsintsconfig.json. Ivy is the only rendering engine since Angular 12, and the option was removed in Angular 15.
- Remove
- org.openrewrite.angular.migration.remove-entry-components
- Remove
entryComponents - Removes the
entryComponentsproperty from@NgModuleand@Componentdecorators, and removes theANALYZE_FOR_ENTRY_COMPONENTSimport. These were removed in Angular 16 as they served no purpose since Ivy.
- Remove
- org.openrewrite.angular.migration.remove-es5-browser-support
- Remove
es5BrowserSupportfromangular.json - Removes the deprecated
es5BrowserSupportoption fromangular.json.es5BrowserSupportwas deprecated in Angular 7.3 and removed in Angular 10. Differential loading is now handled automatically by the Angular CLI based on the project's browserslist configuration.
- Remove
- org.openrewrite.angular.migration.remove-extract-css
- Remove
extractCssfromangular.json - Removes the deprecated
extractCssbuild option fromangular.json. In Angular 11, CSS extraction became the default behavior for production builds and the option was deprecated.
- Remove
- org.openrewrite.angular.migration.remove-ie-polyfills
- Remove IE11 polyfills
- Removes IE11-specific polyfill imports (
core-js,classlist.js,web-animations-js) frompolyfills.tsandangular.json. Angular 13 dropped IE11 support, making these polyfills unnecessary.
- org.openrewrite.angular.migration.remove-module-id
- Remove
moduleId - Removes the
moduleIdproperty from@Componentand@Directivedecorators.moduleIdwas deprecated in Angular 16 and removed in Angular 17 as it served no purpose since Ivy.
- Remove
- org.openrewrite.angular.migration.remove-relative-link-resolution
- Remove
relativeLinkResolution - Removes the
relativeLinkResolutionoption fromRouterModule.forRoot()calls. This option was deprecated in Angular 14 and removed in Angular 15.
- Remove
- org.openrewrite.angular.migration.remove-standalone-true
- Remove redundant
standalone: true - Removes the
standalone: trueproperty from Angular component, directive, and pipe decorators since standalone is the default in Angular 19+.
- Remove redundant
- org.openrewrite.angular.migration.remove-static-false
- Remove
static: falsefrom view queries - Removes
static: falsefrom@ViewChild,@ContentChild,@ViewChildren, and@ContentChildrendecorators. In Angular 9 with Ivy,static: falsebecame the default behavior, making the explicit option unnecessary.
- Remove
- org.openrewrite.angular.migration.remove-zone-js-polyfill
- Remove zone.js polyfill from angular.json
- Removes zone.js entries from the
polyfillsarray inangular.json. Angular 20 supports zoneless change detection viaprovideZonelessChangeDetection(), making the zone.js polyfill unnecessary.
- org.openrewrite.angular.migration.rename-after-render
- Rename
afterRendertoafterEveryRender - Renames
afterRendertoafterEveryRenderin imports and usages. TheafterRenderfunction was renamed toafterEveryRenderin Angular 20, and Angular provides no migration schematic for this change.
- Rename
- org.openrewrite.angular.migration.rename-check-no-changes
- Rename
provideExperimentalCheckNoChangesForDebugtoprovideCheckNoChangesForDebug - Renames
provideExperimentalCheckNoChangesForDebugtoprovideCheckNoChangesForDebugin imports and usages. The experimental API was promoted to developer preview in Angular 20.
- Rename
- org.openrewrite.angular.migration.rename-file
- Rename file
- Renames files matching a glob pattern to a new file name, preserving the directory.
- org.openrewrite.angular.migration.rename-pending-tasks
- Rename
ExperimentalPendingTaskstoPendingTasks - Renames
ExperimentalPendingTaskstoPendingTasksin imports and usages.ExperimentalPendingTaskswas renamed in Angular 19.
- Rename
- org.openrewrite.angular.migration.rename-zoneless-provider
- Rename
provideExperimentalZonelessChangeDetectiontoprovideZonelessChangeDetection - Renames
provideExperimentalZonelessChangeDetectiontoprovideZonelessChangeDetectionin imports and usages. The experimental API was promoted to developer preview in Angular 20.
- Rename
- org.openrewrite.angular.migration.replace-async-with-wait-for-async
- Replace
asyncwithwaitForAsync - Replaces the removed
asynctest helper from@angular/core/testingwithwaitForAsync. Theasyncfunction was deprecated in Angular 11 and removed in Angular 18.
- Replace
- org.openrewrite.angular.migration.replace-deep-zone-js-imports
- Replace deep
zone.jsimports - Replaces legacy deep imports from
zone.jssuch aszone.js/dist/zoneorzone.js/bundles/zone-testing.jswith the standardzone.jsorzone.js/testingimports, in both TypeScript files andangular.jsonpolyfills. Deep imports are no longer allowed in Angular 17.
- Replace deep
- org.openrewrite.angular.migration.replace-http-client-module
- Replace
HttpClientModulewithprovideHttpClient() - Replaces deprecated
HttpClientModule,HttpClientJsonpModule,HttpClientXsrfModule, andHttpClientTestingModulewith their functional equivalents:provideHttpClient()with feature functions andprovideHttpClientTesting().
- Replace
- org.openrewrite.angular.migration.replace-initial-navigation
- Replace
initialNavigationoption values - Replaces deprecated
initialNavigationrouter option values:'legacy_enabled'andtruebecome'enabledBlocking','legacy_disabled'andfalsebecome'disabled', and'enabled'becomes'enabledNonBlocking'. The legacy values were removed in Angular 11;'enabled'was renamed in Angular 14.
- Replace
- org.openrewrite.angular.migration.replace-inject-flags
- Replace
InjectFlagswith options object - Replaces deprecated
InjectFlagsenum usage ininject()calls with the corresponding options object. For example,inject(MyService, InjectFlags.Optional)becomesinject(MyService, \{ optional: true \}).
- Replace
- org.openrewrite.angular.migration.replace-load-children-string
- Replace string-based
loadChildrenwith dynamicimport() - Converts the deprecated string-based
loadChildren: 'path#Module'syntax to dynamic imports:loadChildren: () => import('path').then(m => m.Module).
- Replace string-based
- org.openrewrite.angular.migration.replace-node-sass-with-sass
- Replace
node-sasswithsass - Replaces the deprecated
node-sasspackage withsass(Dart Sass). Angular 12 requires Dart Sass;node-sassis no longer supported.
- Replace
- org.openrewrite.angular.migration.replace-router-link-with-href
- Replace
RouterLinkWithHrefwithRouterLink - Replaces
RouterLinkWithHrefwithRouterLinkin imports and usages.RouterLinkWithHrefwas merged intoRouterLinkin Angular 16.
- Replace
- org.openrewrite.angular.migration.replace-testbed-get-with-inject
- Replace
TestBed.get()withTestBed.inject() - Replaces deprecated
TestBed.get()calls withTestBed.inject().TestBed.get()was deprecated in Angular 9 and removed in Angular 13.
- Replace
- org.openrewrite.angular.migration.replace-untyped-forms
- Replace form classes with untyped variants
- Renames
FormControl,FormGroup,FormArray, andFormBuilderto theirUntyped*equivalents in imports and usages. Angular 14 introduced strictly typed forms, requiring existing untyped usages to migrate to theUntyped*aliases.
- org.openrewrite.angular.migration.replace-validator-with-validators
- Replace
validator/asyncValidatorwith plural forms - Renames the deprecated singular
validatorandasyncValidatorproperty names tovalidatorsandasyncValidators(plural). Angular 10 deprecated the singular forms in favor ofAbstractControlOptions.
- Replace
- org.openrewrite.angular.migration.replace-view-encapsulation-native
- Replace
ViewEncapsulation.NativewithViewEncapsulation.ShadowDom - Replaces
ViewEncapsulation.NativewithViewEncapsulation.ShadowDom.ViewEncapsulation.Nativewas deprecated in Angular 6 and removed in Angular 11.
- Replace
- org.openrewrite.angular.migration.update-component-template-url
- Update component
templateUrl - Updates the
templateUrlproperty value in Angular@Componentdecorators. Useful for refactoring template file paths or standardizing path conventions.
- Update component
- org.openrewrite.angular.migration.update-tsconfig-module
- Update
tsconfig.jsonmodule settings for Ivy - Updates
compilerOptions.moduletoesnextandcompilerOptions.moduleResolutiontonodeintsconfig.json. Angular 9's Ivy compiler requires ES module format. Already-current values likees2020,node16,nodenext, orbundlerare left unchanged.
- Update
- org.openrewrite.angular.migration.update-tsconfig-target
- Update
tsconfig.jsontarget toes2017 - Updates the
compilerOptions.targetintsconfig.jsonfromes5,es2015, ores2016toes2017. Angular 13 dropped IE11 support and requires at least ES2017.
- Update
- org.openrewrite.angular.search.FindAngularComponent
- Find Angular component
- Locates usages of Angular components across the codebase including template elements and other references. If
componentNameisnull, finds all Angular components.
- org.openrewrite.angular.search.find-analyze-for-entry-components-usage
- Find deprecated
ANALYZE_FOR_ENTRY_COMPONENTSusage - Finds usages of the deprecated
ANALYZE_FOR_ENTRY_COMPONENTSinjection token from@angular/core.ANALYZE_FOR_ENTRY_COMPONENTSwas deprecated in Angular 9 and removed in Angular 13.
- Find deprecated
- org.openrewrite.angular.search.find-angular-decorator
- Find Angular decorators
- Finds all Angular decorators like @Component, @Directive, @Injectable, etc.
- org.openrewrite.angular.search.find-angular-http-usage
- Find removed
@angular/httpusage - Finds imports from the
@angular/httpmodule, which was deprecated in Angular 5 and removed in Angular 8. Use@angular/common/http(HttpClient,HttpClientModule) instead.
- Find removed
- org.openrewrite.angular.search.find-animation-driver-matches-element
- Find
AnimationDriver.matchesElementusage - Finds imports of
AnimationDriverfrom@angular/animations/browser, which had itsmatchesElementmethod removed in Angular 18.
- Find
- org.openrewrite.angular.search.find-async-test-helper-usage
- Find deprecated
asynctest helper usage - Finds usages of the deprecated
asynctest helper from@angular/core/testing. Theasyncfunction was deprecated in Angular 11 and should be replaced withwaitForAsync.
- Find deprecated
- org.openrewrite.angular.search.find-bare-module-with-providers
- Find
ModuleWithProviderswithout generic type - Finds imports of
ModuleWithProvidersfrom@angular/core. Starting in Angular 10,ModuleWithProvidersrequires a generic type parameter (e.g.ModuleWithProviders<MyModule>). Ensure all usages specify the module type.
- Find
- org.openrewrite.angular.search.find-browser-transfer-state-module-usage
- Find
BrowserTransferStateModuleusage - Finds usages of
BrowserTransferStateModulefrom@angular/platform-browserwhich was removed in Angular 16.TransferStatecan be used directly without this module.
- Find
- org.openrewrite.angular.search.find-common-module-usage
- Find
CommonModuleusage - Finds imports of
CommonModulefrom@angular/common. Since Angular 19, standalone components are the default andCommonModuleis no longer needed in componentimportsarrays. Built-in directives and pipes are available automatically.
- Find
- org.openrewrite.angular.search.find-compiler-factory-usage
- Find View Engine API usage
- Finds usages of View Engine APIs from
@angular/core(CompilerFactory,Compiler,CompilerOptions,ModuleWithComponentFactories,NgModuleFactory,NgModuleFactoryLoader) which were deprecated in Angular 13.
- org.openrewrite.angular.search.find-date-pipe-default-timezone-usage
- Find
DATE_PIPE_DEFAULT_TIMEZONEusage - Finds usages of
DATE_PIPE_DEFAULT_TIMEZONEwhich was deprecated in Angular 15. UseDATE_PIPE_DEFAULT_OPTIONSwith a\{timezone: '...'\}object value instead.
- Find
- org.openrewrite.angular.search.find-effect-timing-usage
- Find
effect()usage affected by Angular 19 timing changes - Finds
effect()calls from@angular/core. In Angular 19, effects triggered outside change detection now run as part of the change detection process instead of as a microtask, and effects triggered during change detection run earlier, before the component's template.
- Find
- org.openrewrite.angular.search.find-empty-projectable-nodes
- Find
createComponentcalls with emptyprojectableNodes - Finds
createComponent()calls that pass empty arrays inprojectableNodes. In Angular 19, passing an empty array now renders the defaultng-contentfallback content. To suppress fallback content, pass[document.createTextNode('')]instead.
- Find
- org.openrewrite.angular.search.find-fake-async-usage
- Find zone.js-dependent test helper usage
- Finds
fakeAsync(),tick(), andwaitForAsync()calls from@angular/core/testing. These zone.js-dependent test helpers are incompatible with Vitest, the default test runner in Angular 21. Migrate to native async/await patterns instead.
- org.openrewrite.angular.search.find-hammer-js-usage
- Find HammerJS usage
- Finds
HammerModuleimports and HammerJS references. Angular has deprecated HammerJS support and it will be removed in Angular 21.
- org.openrewrite.angular.search.find-i18n-usage
- Find i18n usage
- Finds i18n usage indicators: legacy i18n configuration in
angular.json(i18nLocale,i18nFile,i18nFormat,i18nMissingTranslation),$localizetagged template literals, and@angular/localizeimports. Projects with these markers need@angular/localizeinstalled andimport '@angular/localize/init'inpolyfills.tsfor Angular 9+.
- org.openrewrite.angular.search.find-karma-usage
- Find Karma test runner usage
- Finds Karma test runner configuration in package.json dependencies and angular.json test builder. Angular 21 replaces Karma with Vitest as the default test runner.
- org.openrewrite.angular.search.find-load-children-string-usage
- Find deprecated string-based
loadChildrenusage - Finds usages of the deprecated string-based
loadChildrensyntax (e.g.loadChildren: './path/to/module#ModuleName'). String-based lazy loading was deprecated in Angular 8 and removed in Angular 11. Use dynamic imports instead:loadChildren: () => import('./path/to/module').then(m => m.ModuleName).
- Find deprecated string-based
- org.openrewrite.angular.search.find-missing-injectable
- Find classes with DI dependencies but missing
@Injectable() - Finds classes that have constructor parameters (suggesting dependency injection) but lack an
@Injectable()or other Angular class-level decorator. Angular 9 with Ivy requires an explicit@Injectable()decorator for all services that use dependency injection.
- Find classes with DI dependencies but missing
- org.openrewrite.angular.search.find-ng-class-usage
- Find
NgClassusage - Finds imports of
NgClassfrom@angular/common. ThengClassdirective is soft deprecated in Angular 21 in favor of native[class.*]bindings.
- Find
- org.openrewrite.angular.search.find-ng-style-usage
- Find
NgStyleusage - Finds imports of
NgStylefrom@angular/common. ThengStyledirective is soft deprecated in Angular 21 in favor of native[style.*]bindings.
- Find
- org.openrewrite.angular.search.find-path-match-type-usage
- Find
pathMatchroute properties that may need type narrowing - Finds
pathMatchproperty assignments in route configurations. In Angular 14, thepathMatchtype was narrowed fromstringto'full' | 'prefix'. Routes defined as plain objects without explicitRouteorRoutestyping may fail type checking.
- Find
- org.openrewrite.angular.search.find-platform-dynamic-server-usage
- Find
platformDynamicServerusage - Finds usages of the removed
platformDynamicServerAPI from@angular/platform-server. In Angular 18, replace withplatformServerand addimport '@angular/compiler'.
- Find
- org.openrewrite.angular.search.find-platform-webworker-usage
- Find removed
@angular/platform-webworkerusage - Finds imports from
@angular/platform-webworkerand@angular/platform-webworker-dynamic, which were removed in Angular 8 with no direct replacement.
- Find removed
- org.openrewrite.angular.search.find-platform-worker-usage
- Find
isPlatformWorkerUiandisPlatformWorkerAppusage - Finds usages of the removed
isPlatformWorkerUiandisPlatformWorkerAppAPIs from@angular/common. These were removed in Angular 18 with no replacement, as they served no purpose since the removal of the WebWorker platform.
- Find
- org.openrewrite.angular.search.find-preserve-fragment-usage
- Find deprecated
preserveFragmentusage - Finds usages of the deprecated
preserveFragmentnavigation option.preserveFragmentwas deprecated in Angular 4 and removed in Angular 11. Fragments are now preserved by default.
- Find deprecated
- org.openrewrite.angular.search.find-preserve-query-params-usage
- Find deprecated
preserveQueryParamsusage - Finds usages of the deprecated
preserveQueryParamsnavigation option.preserveQueryParamswas deprecated in Angular 4 and removed in Angular 11. UsequeryParamsHandling: 'preserve'instead.
- Find deprecated
- org.openrewrite.angular.search.find-provided-in-deprecated-usage
- Find deprecated
providedInvalues - Finds usages of
providedIn: 'any'andprovidedIn: NgModulein@InjectableandInjectionTokendeclarations. These were deprecated in Angular 15. UseprovidedIn: 'root'or add the service toNgModule.providersinstead.
- Find deprecated
- org.openrewrite.angular.search.find-reflective-injector-usage
- Find
ReflectiveInjectorusage - Finds usages of
ReflectiveInjectorwhich was removed in Angular 16. UseInjector.createas a replacement.
- Find
- org.openrewrite.angular.search.find-render-application-usage
- Find
renderApplicationusage - Finds usages of
renderApplicationfrom@angular/platform-server. In Angular 16 the signature changed: it no longer accepts a root component as the first argument. Use a bootstrapping function that returnsPromise<ApplicationRef>instead.
- Find
- org.openrewrite.angular.search.find-render-component-type-usage
- Find deprecated
RenderComponentTypeusage - Finds imports of the deprecated
RenderComponentTypefrom@angular/core.RenderComponentTypewas part of the View Engine API, deprecated in Angular 4, and removed in Angular 9.
- Find deprecated
- org.openrewrite.angular.search.find-render-module-factory-usage
- Find
renderModuleFactoryusage - Finds usages of
renderModuleFactoryfrom@angular/platform-serverwhich was removed in Angular 16. UserenderModuleinstead.
- Find
- org.openrewrite.angular.search.find-renderer-usage
- Find deprecated
Rendererusage - Finds imports of the deprecated
Rendererfrom@angular/core.Rendererwas deprecated in Angular 4 and removed in Angular 9. Users should useRenderer2instead.
- Find deprecated
- org.openrewrite.angular.search.find-resource-cache-provider-usage
- Find
RESOURCE_CACHE_PROVIDERusage - Finds usages of the removed
RESOURCE_CACHE_PROVIDERfrom@angular/platform-browser-dynamic. This unused API was removed in Angular 18.
- Find
- org.openrewrite.angular.search.find-root-renderer-usage
- Find deprecated
RootRendererusage - Finds imports of the deprecated
RootRendererfrom@angular/core.RootRendererwas part of the View Engine API, deprecated in Angular 4, and removed in Angular 9. UseRendererFactory2instead.
- Find deprecated
- org.openrewrite.angular.search.find-rxjs-compat-usage
- Find RxJS 5-style imports requiring
rxjs-compat - Finds imports using RxJS 5-style deep import paths (e.g.
rxjs/Observable,rxjs/add/operator/map) that require therxjs-compatpackage. These should be migrated to RxJS 6+ import paths before removingrxjs-compat.
- Find RxJS 5-style imports requiring
- org.openrewrite.angular.search.find-server-transfer-state-module-usage
- Find
ServerTransferStateModuleusage - Finds usages of the removed
ServerTransferStateModulefrom@angular/platform-server. In Angular 18,TransferStateworks without providing this module.
- Find
- org.openrewrite.angular.search.find-setup-testing-router-usage
- Find
setupTestingRouterusage - Finds usages of the removed
setupTestingRouterfunction from@angular/router/testing. This function was removed in Angular 17. UseRouterModule.forRootorprovideRouterto set up the Router for tests instead.
- Find
- org.openrewrite.angular.search.find-testability-pending-request-usage
- Find removed Testability pending request methods
- Finds imports of
Testabilityfrom@angular/core, which hadincreasePendingRequestCount,decreasePendingRequestCount, andgetPendingRequestCountremoved in Angular 18. These are now tracked with zones.
- org.openrewrite.angular.search.find-undecorated-angular-class
- Find undecorated classes with Angular features
- Finds classes that use Angular member decorators (
@Input,@Output,@ViewChild, etc.) or implement lifecycle hooks (ngOnInit,ngOnDestroy, etc.) but lack a class-level Angular decorator. Angular 9 with Ivy requires all classes using Angular features to have an explicit decorator.
- org.openrewrite.angular.search.find-with-no-dom-reuse-usage
- Find
withNoDomReuseusage - Finds usages of the removed
withNoDomReusefunction from@angular/platform-browser. This function was removed in Angular 17. To disable hydration, remove theprovideClientHydration()call from your providers or use thengSkipHydrationattribute on specific components.
- Find
- org.openrewrite.angular.search.find-wrapped-value-usage
- Find deprecated
WrappedValueusage - Finds usages of the deprecated
WrappedValuefrom@angular/core.WrappedValuewas deprecated in Angular 11 and removed in Angular 13.
- Find deprecated
- org.openrewrite.angular.search.find-zone-js-usage
- Find zone.js usage
- Finds zone.js imports and NgZone references. Angular 20 supports zoneless change detection via
provideZonelessChangeDetection(), making zone.js optional.
rewrite-cryptography
- io.moderne.cryptography.FindCryptoVulnerabilitiesPipeline
- Find cryptographic vulnerability chains
- Detects cryptographic vulnerabilities that span multiple operations, tracking flow from hardcoded algorithms through key material to encryption operations.
- io.moderne.cryptography.FindDirectSSLConfigurationEditing
- Find direct SSL configuration editing
- Detects direct configuration of protocols or cipher suites on SSL objects like SSLSocket, SSLServerSocket, or SSLEngine. This pattern makes SSL/TLS configuration scattered throughout the codebase and prevents centralized security policy management, hindering crypto-agility.
- io.moderne.cryptography.FindHardcodedAlgorithmChoice
- Find hardcoded algorithm choices
- Detects hardcoded algorithm choices in cryptographic operations. Hardcoded algorithms prevent easy migration to stronger or quantum-resistant algorithms when needed. This is a critical crypto-agility issue that makes systems vulnerable to future attacks.
- io.moderne.cryptography.FindHardcodedAlgorithmParameters
- Find hardcoded algorithm-specific parameters
- Detects hardcoded algorithm-specific parameters like RSA public exponents or EC curve parameters. These hardcoded values prevent algorithm agility and may use weak or non-standard parameters that compromise security.
- io.moderne.cryptography.FindHardcodedCertificate
- Find hardcoded certificates
- Detects hardcoded certificates in the code, including certificates that are hardcoded as strings and used to generate X509Certificate instances via CertificateFactory. Hardcoded certificates can lead to security issues when they expire or need to be revoked.
- io.moderne.cryptography.FindHardcodedCiphersuiteChoice
- Find hardcoded cipher suite choices
- Detects hardcoded cipher suite choices used in SSL/TLS configurations. Hardcoded cipher suites prevent easy updates when cipher suites become weak or need to be changed for compliance reasons.
- io.moderne.cryptography.FindHardcodedKeyLength
- Find hardcoded cryptographic key lengths
- Detects hardcoded key lengths used in cryptographic operations like KeyGenerator.init(), KeyPairGenerator.initialize(), RSAKeyGenParameterSpec, and PBEKeySpec. Hardcoded key lengths reduce flexibility and may not meet changing security requirements.
- io.moderne.cryptography.FindHardcodedPrivateKey
- Find hardcoded private keys
- Detects hardcoded private keys in the code, including PEM-encoded keys that flow into KeyFactory.generatePrivate() calls. Hardcoded private keys are a severe security vulnerability as they compromise the entire cryptographic system.
- io.moderne.cryptography.FindHardcodedProtocolChoice
- Find hardcoded SSL/TLS protocol choices
- Detects hardcoded SSL/TLS protocol choices like 'TLSv1.2', 'SSLv3' used in SSLContext.getInstance() and setProtocols() calls. Hardcoded protocols prevent easy updates when protocols become obsolete or insecure.
- io.moderne.cryptography.FindHardcodedProviderName
- Find hardcoded cryptographic provider names
- Detects hardcoded cryptographic provider names (like 'BC', 'SunJCE') used in getInstance() calls. Hardcoding provider names reduces portability and can cause issues when the provider is not available on different systems.
- io.moderne.cryptography.FindProgrammaticProviderEditing
- Find programmatic security provider editing
- Detects programmatic modifications to the Java Security Provider list through Security.addProvider(), insertProviderAt(), or removeProvider() calls. Modifying providers at runtime makes the security configuration unpredictable and prevents crypto-agility by hardcoding provider dependencies.
- io.moderne.cryptography.FindRSAKeyGenParameters
- Find RSA key generation parameters
- Finds RSAKeyGenParameterSpec instantiations and extracts their parameter values into a data table.
- io.moderne.cryptography.FindSSLContextSetDefault
- Find SSLContext.setDefault() usage
- Detects calls to SSLContext.setDefault() which sets the system-wide default SSL context. This is problematic because it affects all SSL/TLS connections in the JVM, potentially overriding security configurations set by other parts of the application or libraries. It also prevents crypto-agility as the configuration becomes global.
- io.moderne.cryptography.FindSSLSocketParameters
- Find SSL socket configuration parameters
- Finds SSLSocket setter method invocations and extracts their parameter values into a data table.
- io.moderne.cryptography.FindSecurityModifications
- Find Security class modifications
- Finds invocations of java.security.Security methods that modify security configuration such as removeProvider, addProvider, insertProviderAt, setProperty, and removeProperty.
- io.moderne.cryptography.FindSecuritySetProperties
- Find
Security.setProperty(..)calls for certain properties - There is a defined set of properties that should not be set using
Security.setProperty(..)as they can lead to security vulnerabilities.
- Find
- io.moderne.cryptography.PostQuantumCryptography
- Post quantum cryptography
- This recipe searches for instances in code that may be impacted by post quantum cryptography. Applications may need to support larger key sizes, different algorithms, or use crypto agility to handle the migration. The recipe includes detection of hardcoded values that affect behavior in a post-quantum world, programmatic configuration that may prevent algorithm changes, and general cryptographic usage patterns that should be reviewed.
rewrite-devcenter
- io.moderne.devcenter.ApacheDevCenter
- DevCenter for Apache
- A DevCenter that tracks the latest Apache Maven parent POM versions and applies best practices.
- io.moderne.devcenter.ApacheMavenBestPractices
- Apache Maven best practices
- A collection of recipes that apply best practices to Maven POMs. Some of these recipes affect build stability, so they are reported as security issues in the DevCenter card.
- io.moderne.devcenter.ApacheMavenDevCenter
- DevCenter for Apache Maven
- A DevCenter that tracks the latest Apache Maven parent POM versions and applies best practices. This DevCenter includes recipes to upgrade the parent POMs of Apache Maven, as well as a collection of best practices for Maven POMs.
- io.moderne.devcenter.BuildToolCard
- Build tool
- Track build tool versions across repositories.
- io.moderne.devcenter.BuildToolStarter
- DevCenter for Gradle and Maven
- Track and automate upgrades for Gradle, Maven, and Java versions.
- io.moderne.devcenter.CSharpVersionUpgrade
- Move to a later .NET version
- Determine the current state of a repository relative to a desired .NET version upgrade.
- io.moderne.devcenter.DependencyVulnerabilityCheck
- Vulnerabilities status
- Determine the current state of a repository relative to its vulnerabilities.
- io.moderne.devcenter.DevCenterCSharpStarter
- DevCenter for C#
- A default DevCenter configuration for C# repositories. Track .NET version adoption across your organization.
- io.moderne.devcenter.DevCenterNodeStarter
- DevCenter for Node.js
- A default DevCenter configuration for Node.js repositories. Track Node.js version adoption across your organization.
- io.moderne.devcenter.DevCenterPythonStarter
- DevCenter for Python
- A default DevCenter configuration for Python repositories. Track Python version adoption across your organization.
- io.moderne.devcenter.DevCenterStarter
- DevCenter
- This is a default DevCenter configuration that can be used as a starting point for your own DevCenter configuration. It includes a combination of upgrades, migrations, and security fixes. You can customize this configuration to suit your needs. For more information on how to customize your DevCenter configuration, see the DevCenter documentation.
- io.moderne.devcenter.FindOrganizationStatistics
- Find organization statistics
- Counts lines of code per repository for organization-level statistics.
- io.moderne.devcenter.GroovyVersionUpgrade
- Move to a later Groovy version
- Determine the current state of a repository relative to a desired Groovy version upgrade.
- io.moderne.devcenter.JUnitJupiterUpgrade
- Move to JUnit 6
- Move to JUnit Jupiter.
- io.moderne.devcenter.JavaVersionUpgrade
- Move to a later Java version
- Determine the current state of a repository relative to a desired Java version upgrade.
- io.moderne.devcenter.KotlinVersionUpgrade
- Move to a later Kotlin version
- Determine the current state of a repository relative to a desired Kotlin version upgrade.
- io.moderne.devcenter.LibraryUpgrade
- Library upgrade
- Determine the current state of a repository relative to a desired library upgrade.
- io.moderne.devcenter.NodeVersionUpgrade
- Move to a later Node.js version
- Determine the current state of a repository relative to a desired Node.js version upgrade.
- io.moderne.devcenter.ParentPomUpgrade
- Parent POM upgrade
- Determine the current state of a repository relative to a desired parent POM upgrade.
- io.moderne.devcenter.PythonVersionUpgrade
- Move to a later Python version
- Determine the current state of a repository relative to a desired Python version upgrade.
- io.moderne.devcenter.QuarkusDevCenter
- DevCenter for Quarkus
- A DevCenter that tracks the latest Quarkus framework versions and applies best practices. This DevCenter includes recipes to upgrade Quarkus versions, migrate from deprecated APIs, and ensure compatibility with the latest Java versions and testing frameworks.
- io.moderne.devcenter.ReportAsSecurityIssues
- Report as security issues
- Look for results produced by recipes in the same recipe list that this recipe is part of, and report them as security issues in DevCenter.
- io.moderne.devcenter.ScalaVersionUpgrade
- Move to a later Scala version
- Determine the current state of a repository relative to a desired Scala version upgrade.
- io.moderne.devcenter.SecurityStarter
- OWASP top ten
- This recipe is a starter card to reveal common OWASP Top 10 issues in your source code. You can customize this configuration to suit your needs. For more information on how to customize your DevCenter configuration, see the DevCenter documentation.
- io.moderne.devcenter.UpgradeApacheParent
- Upgrade Apache Parent POM
- Upgrades the Apache parent POM to the latest version.
- io.moderne.devcenter.UpgradeMavenParent
- Upgrade Apache Maven Parent
- Upgrades the Apache Maven parent POM to the latest version.
- io.moderne.devcenter.UpgradeMavenPluginsParent
- Upgrade Maven Plugins Parent
- Upgrades the Apache Maven parent POM to the latest version.
- io.moderne.devcenter.UpgradeMavenSharedParent
- Upgrade Maven Shared Parent
- Upgrades the Apache Maven parent POM to the latest version.
- io.moderne.devcenter.UpgradeQuarkus3_x
- Upgrade to Quarkus 3.26
- Upgrades Quarkus dependencies to version 3.26.x, including core, extensions, and tooling.
- io.moderne.devcenter.UpgradeQuarkusUniverseBom
- Upgrade Quarkus Universe BOM
- Upgrades the Quarkus Universe BOM parent to the latest version.
- io.moderne.devcenter.VulnerabilitiesDevCenter
- DevCenter for Vulnerability Management
- Recipes to analyze and manage dependency vulnerabilities using Moderne DevCenter.
rewrite-dropwizard
- io.moderne.java.dropwizard.MigrateToDropwizard5
- Migrate to Dropwizard 5.0.x from 4.x
- Apply changes required to upgrade a Dropwizard 4.x application to 5.0.x. This includes upgrading dependencies, removing deprecated configuration options, and migrating Jetty handler implementations. Includes required migrations to Java 17, Jakarta EE 10, JUnit 5, Jackson 2.x, and Hibernate 6.6. See the upgrade guide.
- io.moderne.java.dropwizard.boot.MigrateApplicationRunMethod
- Migrate Dropwizard Application.run() to SpringApplication.run()
- Replaces the
new MyApp().run(args)pattern in the main method withSpringApplication.run(MyApp.class, args).
- io.moderne.java.dropwizard.boot.MigrateDropwizardToSpringBoot3
- Migrate Dropwizard to Spring Boot 3
- Migrate a Dropwizard application to Spring Boot 3. First applies the Dropwizard to Spring Boot 2.7 migration, then adds managed lifecycle and health check migrations on top.
- io.moderne.java.dropwizard.boot.annotation.AddClassAnnotationIfAnnotationExists
- Add annotation if target annotation exists
- Adds an annotation to a class if it already has a specified target annotation.
- io.moderne.java.dropwizard.boot.annotation.AddClassAnnotationIfSuperTypeExists
- Add annotation if target supertype exists
- Adds an annotation to a class if it extends or implements a specified target type.
- io.moderne.java.dropwizard.boot.datasource.RemoveDataSourceFactoryBuildChain
- Replace DataSourceFactory build chain with @Autowired DataSource
- Replaces
DataSourceFactory.build(MetricRegistry, String)variable declarations with@Autowired DataSourcefields. Spring Boot auto-configures the DataSource fromspring.datasource.*properties. Note: connection pool metrics previously wired viaMetricRegistryrequirespring-boot-starter-actuatorfor equivalent observability.
- io.moderne.java.dropwizard.boot.datasource.RemoveLifecycleManageCalls
- Remove Dropwizard lifecycle.manage() calls
- Removes
environment.lifecycle().manage()calls. Spring Boot manages bean lifecycle automatically through its IoC container.
- io.moderne.java.dropwizard.boot.general.RemoveMethodsByPackage
- Remove methods referencing specified package
- Removes any method that has a return type or parameter type from the specified package.
- io.moderne.java.dropwizard.boot.general.RemoveVariablesByPackage
- Remove class variables matching package filter
- Removes variable declarations whose type belongs to the specified package.
- io.moderne.java.dropwizard.boot.health.MigrateHealthCheckMethod
- Migrate Dropwizard health check Result calls and wrap exceptions
- Transforms
Result.healthy()/Result.unhealthy()calls toHealth.up().build()/Health.down().build()and wraps throwingcheck()methods in try-catch.
- io.moderne.java.dropwizard.boot.jackson.ReplaceJacksonNewObjectMapper
- Replace
Jackson.newObjectMapper()withnew ObjectMapper().findAndRegisterModules() - Replaces Dropwizard's
Jackson.newObjectMapper()withnew ObjectMapper().findAndRegisterModules(), which provides equivalent module auto-discovery using the standard Jackson SPI mechanism.
- Replace
- io.moderne.java.dropwizard.boot.lifecycle.MigrateManagedLifecycle
- Add lifecycle annotations to Dropwizard Managed methods
- Adds
@PostConstructtostart()and@PreDestroytostop()on classes implementingio.dropwizard.lifecycle.Managed.
- io.moderne.java.dropwizard.boot.method.ChangeSuperType
- Change supertype
- Changes the supertype of a class, optionally converting from extends to implements.
- io.moderne.java.dropwizard.boot.method.RemoveSuperTypeByType
- Remove supertype by fully qualified name
- Removes a specified type from class extends or implements clauses.
- io.moderne.java.dropwizard.boot.method.RemoveUnnecessaryOverride
- Remove unnecessary
@Overrideannotations - Removes
@Overrideannotations from methods that don't actually override or implement any method. This helps maintain clean code by removing incorrect annotations that could be misleading.
- Remove unnecessary
- io.moderne.java.dropwizard.boot.method.RemoveUnnecessarySuperCalls
- Remove
supercalls when the class does not extend another class - Removes calls to
super(...)orsuper.someMethod(...)if the class does not have a real superclass besidesjava.lang.Object.
- Remove
- io.moderne.java.dropwizard.boot.test.DropwizardRulesJUnit4ToSpringBoot
- Replace Dropwizard rules with Spring Boot test configuration
- Remove Dropwizard JUnit4 rules and add Spring Boot test annotations and extensions.
- io.moderne.java.dropwizard.boot.test.MethodLambdaExtractor
- Inline lambda body from matched method invocations
- Extracts the body of lambda expressions passed to matched method invocations and inlines them into the surrounding code.
- io.moderne.java.dropwizard.boot.test.MockitoVariableToMockBean
- Convert Mockito mock() to @MockBean
- Converts static final Mockito mock fields to Spring Boot @MockBean fields.
- io.moderne.java.dropwizard.boot.test.TransformDropwizardRuleInvocations
- Convert Dropwizard test rule calls to RestTemplate
- Transforms Dropwizard AppRule and ResourceTestRule testing calls to their equivalent RestTemplate calls.
- io.moderne.java.dropwizard.dw5.MigrateJettyHandlerSignature
- Migrate Jetty
AbstractHandlerto Jetty 12Handler.Abstract - Migrates custom Jetty handler implementations from Jetty 11's
AbstractHandler(used in Dropwizard 4.x) to Jetty 12'sHandler.Abstract(used in Dropwizard 5.x). This changes thehandlemethod signature and updatesbaseRequest.setHandled(true)to useCallbackand returntrue.
- Migrate Jetty
rewrite-elastic
- io.moderne.elastic.elastic9.ChangeApiNumericFieldType
- Change numeric field type with conversion
- Adds conversion methods with null checks for numeric type changes in Elasticsearch 9 API.
- io.moderne.elastic.elastic9.ChangeApiNumericFieldTypes
- Change numeric field types for Elasticsearch 9
- Handles changes between different numeric types (
LongtoInteger,inttoLong...) in Elasticsearch 9 API responses by adding appropriate conversion methods with null checks.
- io.moderne.elastic.elastic9.MigrateDenseVectorElementType
- Migrate DenseVectorProperty.elementType from String to DenseVectorElementType enum
- In Elasticsearch 9,
DenseVectorProperty.elementType()returnsDenseVectorElementTypeenum instead ofString, and the builder methodelementType(String)now accepts the enum type. This recipe handles both builder calls and getter calls.
- io.moderne.elastic.elastic9.MigrateDenseVectorSimilarity
- Migrate DenseVectorProperty.similarity from String to DenseVectorSimilarity enum
- In Elasticsearch 9,
DenseVectorProperty.similarity()returnsDenseVectorSimilarityenum instead ofString, and the builder methodsimilarity(String)now accepts the enum type. This recipe handles both builder calls and getter calls.
- io.moderne.elastic.elastic9.MigrateMatchedQueries
- Migrate
matchedQueriesfrom List to Map - In Elasticsearch Java Client 9.0,
Hit.matchedQueries()changed from returningList<String>toMap<String, Double>. This recipe migrates the usage by adding.keySet()for iterations and usingnew ArrayList<>(result.keySet())for assignments.
- Migrate
- io.moderne.elastic.elastic9.MigrateScriptSource
- Migrate script source from String to Script/ScriptSource
- Migrates
Script.source(String)calls to useScriptSource.scriptString(String)wrapper in Elasticsearch Java client 9.x.
- io.moderne.elastic.elastic9.MigrateSpanTermQueryValue
- Migrate
SpanTermQuery.value()from String to FieldValue - In Elasticsearch 9,
SpanTermQuery.value()returns aFieldValueinstead ofString. This recipe updates calls to handle the new return type by checking if it's a string and extracting the string value.
- Migrate
- io.moderne.elastic.elastic9.MigrateToElasticsearch9
- Migrate from Elasticsearch 8 to 9
- This recipe performs a comprehensive migration from Elasticsearch 8 to Elasticsearch 9, addressing breaking changes, API removals, deprecations, and required code modifications.
- io.moderne.elastic.elastic9.RenameApiField
- Rename
Elasticsearch valueBody()methods - In Elasticsearch Java Client 9.0, the generic
valueBody()method andvalueBody(...)builder methods have been replaced with specific getter and setter methods that better reflect the type of data being returned. Similarly, forGetRepositoryResponse, theresultfield also got altered torepositories.
- Rename
- io.moderne.elastic.elastic9.RenameApiFields
- Rename API fields for Elasticsearch 9
- Renames various API response fields from
valueBodyto align with Elasticsearch 9 specifications.
- io.moderne.elastic.elastic9.UseNamedValueParameters
- Use NamedValue parameters instead of Map
- Migrates
indicesBoostanddynamicTemplatesparameters fromMaptoNamedValuein Elasticsearch Java client 9.x.
rewrite-hibernate
- io.moderne.hibernate.MigrateToHibernate40
- Migrate to Hibernate 4.0.x
- This recipe will apply changes commonly needed when migrating from Hibernate 3.x to 4.0.x, including migration of collection annotations to their JPA 2.0 equivalents.
- io.moderne.hibernate.MigrateToHibernate60
- Migrate to Hibernate 6.0.x (Moderne Edition)
- This recipe will apply changes commonly needed when migrating to Hibernate 6.0.x.
- io.moderne.hibernate.MigrateToHibernate66
- Migrate to Hibernate 6.6.x (Moderne Edition)
- This recipe will apply changes commonly needed when migrating to Hibernate 6.6.x.
- io.moderne.hibernate.MigrateToHibernate70
- Migrate to Hibernate 7.0.x (Moderne Edition)
- This recipe will apply changes commonly needed when migrating to Hibernate 7.0.x.
- io.moderne.hibernate.MigrateToHibernate71
- Migrate to Hibernate 7.1.x (Moderne Edition)
- This recipe will apply changes commonly needed when migrating to Hibernate 7.0.x.
- io.moderne.hibernate.MigrateToHibernate72
- Migrate to Hibernate 7.2.x
- This recipe will apply changes commonly needed when migrating to Hibernate 7.2.x.
- io.moderne.hibernate.search.FindJPQLDefinitions
- Find JPQL definitions
- Find Java Persistence Query Language definitions in the codebase.
- io.moderne.hibernate.update40.IndexHqlAnnotationPositionalParameters
- Index HQL/JPQL positional parameters in annotations
- Replaces unindexed
?positional parameters with indexed?1,?2, etc. in an HQL/JPQL query string held in an annotation attribute matching the given pattern.
- io.moderne.hibernate.update40.IndexHqlMethodPositionalParameters
- Index HQL/JPQL positional parameters in method calls
- Replaces unindexed
?positional parameters with indexed?1,?2, etc. in an HQL/JPQL query string passed as the first argument of a method matching the given pattern.
- io.moderne.hibernate.update40.MigrateJoinTableToCollectionTable
- Migrate
@JoinTableto@CollectionTablefor element collections - Replaces
@JoinTablewith@CollectionTablewhen used alongside@CollectionOfElementsor@ElementCollection.@CollectionTableis the JPA 2.0 standard for defining the table that stores element collections. WheninverseJoinColumnsis present, its column name is preserved as a@Columnannotation.
- Migrate
- io.moderne.hibernate.update60.MigrateHibernateCriteriaToJpaCriteria
- Migrate Hibernate Criteria API to JPA Criteria API
- Migrates code using the legacy Hibernate Criteria API (org.hibernate.Criteria, org.hibernate.criterion.) to the JPA Criteria API (jakarta.persistence.criteria.). Handles common patterns including Restrictions (with and/or), Order, Projections, list(), and uniqueResult().
- io.moderne.hibernate.update60.MigrateRemovedUuidTypes
- Migrate removed Hibernate UUID
@Typeto@JdbcTypeCode - Hibernate 6.x removed
UUIDCharType,UUIDBinaryTypeandPostgresUUIDType. Replace@Typeannotations referencing these with@JdbcTypeCodeand the correspondingSqlTypesconstant.
- Migrate removed Hibernate UUID
- io.moderne.hibernate.update66.FixConflictingClassTypeAnnotations
- Fix conflicting class type annotation Hibernate 6.6
- Since Hibernate 6.6 a mapped class can have either
@MappedSuperclassor@Embeddable, or@Entity. This recipe removes@Entityfrom classes annotated with@MappedSuperclassor@Embeddable. For the moment die combination of@MappedSuperclassor@Embeddableis advised to migrate to Single Table Inheritance but still accepted and therefore stays.
- io.moderne.hibernate.update66.MigrateCascadeTypes
- Migrate Hibernate CascadeType constants
- Moving away from deprecated Hibernate CascadeType constants. CascadeType.SAVE_UPDATE -> CascadeType.PERSIST and/or CascadeType.MERGE, CascadeType.DELETE -> CascadeType.REMOVE.
- io.moderne.hibernate.update66.RemoveTableFromInheritedEntity
- Remove table from single table inherited entity
- For Single Table Inherited Entities Hibernate ignores the
@Tableannotation on child entities. From Version 6.6 it is considered an error.
- io.moderne.hibernate.update70.AddCascadePersistToIdMappedAssociations
- Migrate implicit cascade=PERSIST for @Id and @MapsId associations
- Hibernate used to automatically enable cascade=PERSIST for association fields annotated @Id or @MapsId. This was undocumented and unexpected behavior, and no longer supported in Hibernate 7. Existing code which relies on this behavior will be modified by addition of explicit cascade=PERSIST to the association fields.
- io.moderne.hibernate.update70.CompositeUserTypeSessionFactoryImplementor
- Remove leaking of SessionFactoryImplementor from
org.hibernate.usertype.CompositeUserTypeinvocations and implementations - Remove leaking of SessionFactoryImplementor from
org.hibernate.usertype.CompositeUserTypeinvocations and implementations.
- Remove leaking of SessionFactoryImplementor from
- io.moderne.hibernate.update70.FindNativeQueryRawEnumParameters
- Find native queries with enum parameters requiring SpEL conversion
- When using
@NativeQueryor@Query(nativeQuery = true), enum parameters are not automatically converted by JPA. This recipe finds native queries with raw enum bind parameters that need SpEL expressions like:#\{#status.name()\}or:#\{#status.ordinal()\}depending on how the enum is persisted.
- io.moderne.hibernate.update70.MigrateConfigurableToGeneratorCreationContext
- Migrate
Configurable.configure()to useGeneratorCreationContext - In Hibernate 7.0,
Configurable.configure()now takes aGeneratorCreationContextparameter instead ofServiceRegistry. This recipe migrates method signatures and call sites.
- Migrate
- io.moderne.hibernate.update70.MigrateIntegratorMethod
- Migrate Hibernate
Integrator#integratemethod - Migrate Hibernate
Integrator#integratemethod from deprecated signature to Hibernate 7 compatible signature. Changesintegrate(Metadata, SessionFactoryImplementor, SessionFactoryServiceRegistry)tointegrate(Metadata, BootstrapContext, SessionFactoryImplementor).
- Migrate Hibernate
- io.moderne.hibernate.update70.MigrateJdbcTypeToJdbcTypeCode
- Migrate @JdbcType to @JdbcTypeCode
- In Hibernate 7.0, various JDBC types were moved to internal packages. Use @JdbcTypeCode with SqlTypes constants instead of @JdbcType with specific classes.
- io.moderne.hibernate.update70.MigrateJpqlTruncToDateCast
- Migrate JPQL
trunc()tocast(... as date) - Hibernate 7 maps the JPQL
trunc()function to numeric truncation only (SQL standard). For date truncation, single-argumenttrunc(expr)must be replaced withcast(expr as date).
- Migrate JPQL
- io.moderne.hibernate.update70.MigrateLockOptionsToDirectParameters
- Migrate LockOptions to direct parameters
- Migrates deprecated
LockOptionsusage to direct parameters in method calls. As of JPA 3.2 and Hibernate 7,LockMode,Timeout, andPessimisticLockScopeare passed directly tofind(),refresh(), andlock()methods instead of being wrapped in aLockOptionsobject.
- io.moderne.hibernate.update70.MigrateMetamodelImplementor
- Migrate
MetamodelImplementorto Hibernate 7.0 - In Hibernate 7.0,
MetamodelImplementorhas been split intoMappingMetamodelfor ORM-specific operations andJpaMetamodelfor JPA-standard operations. This recipe migrates the usage based on which methods are called.
- Migrate
- io.moderne.hibernate.update70.MigrateNaturalIdLoadAccess
- Migrate NaturalIdLoadAccess method calls
- Migrates NaturalIdLoadAccess#using(Object...) to using(Map.of(...)) variants for Hibernate 7.0.
- io.moderne.hibernate.update70.MigrateNaturalIdMultiLoadAccess
- Migrate NaturalIdMultiLoadAccess method calls
- Migrates NaturalIdMultiLoadAccess#compoundValue(Object...) to Map.of(...) variants for Hibernate 7.0.
- io.moderne.hibernate.update70.MigrateQueryToNativeQuery
- Migrate @Query to @NativeQuery for unsupported JPQL
- Converts Spring Data
@Queryannotations to@NativeQuerywhen the JPQL query contains patterns unsupported by Hibernate 7's stricter JPQL parser, such as multi-argumenttrunc(date, 'format').
- io.moderne.hibernate.update70.MigrateSessionInterface
- Migrate Session interface method calls
- Migrates code using deprecated Session interface methods to their Hibernate 7.0 replacements.
- io.moderne.hibernate.update70.MigrateSessionToDeferToJPA
- Migrate Session save/update/delete method calls
- Migrates code using deprecated Session load/get/refresh/save/update/delete methods to their Hibernate 7.0 replacements.
- io.moderne.hibernate.update70.MigrateSetFlushModeToSetQueryFlushMode
- Migrate
setFlushMode()tosetQueryFlushMode() - In Hibernate 7.0,
CommonQueryContract.setFlushMode(FlushModeType)has been replaced withsetQueryFlushMode(QueryFlushMode). This recipe migrates the method call and convertsFlushModeTypeparameters to theirQueryFlushModeequivalents.
- Migrate
- io.moderne.hibernate.update70.MigrateToHibernate7JFR
- Migrate to Hibernate 7 JFR APIs
- Migrates deprecated JFR integration APIs to their Hibernate 7 replacements.
EventManagerbecomesEventMonitorandHibernateMonitoringEventbecomesDiagnosticEvent.
- io.moderne.hibernate.update70.MigrateToTargetEmbeddable
- Migrate to @TargetEmbeddable
- Migrates code using removed @Target to to Hibernate 7.0's @TargetEmbeddable equivalent. Removes misused @Target annotations.
- io.moderne.hibernate.update70.RemoveUnnecessaryCastToSession
- Remove unnecessary cast to
SessionforSessionFactory.createEntityManager() - In Hibernate 7.0,
SessionFactory.createEntityManager()explicitly returns Session, making casts to Session unnecessary.
- Remove unnecessary cast to
- io.moderne.hibernate.update70.ReplaceHibernateWithJakartaAnnotations
- Replace hibernate annotations with Jakarta variants
- Tries to replaces annotations that have been removed in Hibernate 7.0 with its Jakarta equivalent, such as Table, @Where, @OrderBy, etc. If a annotation is used with arguments that do not have a direct replacement, the annotation is not replaced at all.
- io.moderne.hibernate.update70.ReplaceSessionLockRequest
- Replace Session.buildLockRequest with LockOptions
- Migrates Session.buildLockRequest(LockOptions.X) calls to use session.lock(entity, new LockOptions(LockMode.X)) in Hibernate 7.0.
- io.moderne.hibernate.update70.UnboxingTransactionTimeout
- Null safe Transaction#getTimeout()
- JPA 3.2 adds
#getTimeoutbut usesIntegerwhereas Hibernate has historically usedint. Note that this raises the possibility of aNullPointerExceptionduring migration if, e.g., performing direct comparisons on the timeout value against an in (auto unboxing). This recipe adds ternary operators whereTransaction#getTimeout()is used and a negative value will be used if thegetTimeout()resulted in a null value.
- io.moderne.hibernate.update70.UserTypeNullSafeGetSharedSessionContractImplementorRecipe
- Remove leaking of SharedSessionContractImplementor from
org.hibernate.usertype.UserTypeinvocations - Remove leaking of SharedSessionContractImplementor from
org.hibernate.usertype.UserTypeinvocations.
- Remove leaking of SharedSessionContractImplementor from
- io.moderne.hibernate.update70.UserTypeSharedSessionContractImplementor
- Remove leaking of SharedSessionContractImplementor from
org.hibernate.usertype.UserTypeimplementations - Remove leaking of SharedSessionContractImplementor from
org.hibernate.usertype.UserTypeimplementations.
- Remove leaking of SharedSessionContractImplementor from
rewrite-jasperreports
- io.moderne.jasperreports.MigrateExporterConfigToJasper6
- Update JasperReports exporter configuration
- Updates deprecated exporter parameter imports to the new configuration classes introduced in JasperReports 6. This includes migrating from parameter classes to configuration classes for PDF, HTML, CSV, and other exporters.
- io.moderne.jasperreports.MigrateXlsToXlsxExporter
- Migrate JRXlsExporter to JRXlsxExporter
- Migrates the deprecated
JRXlsExporterto the newJRXlsxExporterclass in JasperReports 6. Also updates related configuration classes from XLS to XLSX variants.
- io.moderne.jasperreports.UpgradeToJasperReports5
- Migrate to JasperReports 5.6.x
- Migrates JasperReports from 4.6.0 to 5.6.x. This recipe includes minimal breaking changes, allowing teams to test and validate the migration before proceeding to version 6.
- io.moderne.jasperreports.UpgradeToJasperReports6
- Migrate to JasperReports 6
- Migrates JasperReports from 5.x to 6.x with the new exporter API, XLS to XLSX move, and removal of Spring JasperReports views.
- io.moderne.jasperreports.v5.MigrateExporterSetParameter
- Migrate JasperReports exporter setParameter to new API
- Migrates deprecated
setParametercalls on JasperReports exporters to the new API usingsetExporterInputandsetExporterOutput.
- io.moderne.jasperreports.v5.MigratePrintServiceExporterConfiguration
- Migrate JRPrintServiceExporterParameter to SimplePrintServiceExporterConfiguration
- Migrates
JRPrintServiceExporterParametersetParameter calls to useSimplePrintServiceExporterConfiguration.
rewrite-java-application-server
- io.moderne.java.server.jboss.ModuleHasJBossDescriptor
- Module has JBoss descriptor
- Searches for modules containing JBoss descriptor files (
jboss-web.xml,jboss-deployment-structure.xml). Places aSearchResultmarker on all source files within a module with a JBoss descriptor. This recipe is intended to be used as a precondition for other recipes.
- io.moderne.java.server.jboss.MoveWebXml
- Move
web.xmlto resources - Moves
src/main/webapp/WEB-INF/web.xmltosrc/main/resources/web.xml.
- Move
- io.moderne.java.server.jboss.PlanJBossMigration
- Plan JBoss migration
- Analyzes the repository to plan a JBoss migration, identifying JBoss descriptor files (jboss-web.xml, jboss-deployment-structure.xml) and recording them in a data table.
- io.moderne.java.server.jboss.jetty.ConfigureGradleApplicationPlugin
- Configure Gradle
applicationplugin main class - Adds or updates
application \{ mainClass = '...' \}in a Gradle build script. Supports both Groovy DSL (build.gradle) and Kotlin DSL (build.gradle.kts).
- Configure Gradle
- io.moderne.java.server.jboss.jetty.ConfigureGradleFatJar
- Configure Gradle
jartask for fat JAR - Configures the Gradle
jartask to produce a self-contained fat JAR with all runtime dependencies bundled. Supports both Groovy DSL (build.gradle) and Kotlin DSL (build.gradle.kts).
- Configure Gradle
- io.moderne.java.server.jboss.jetty.CreateJettyEnvXml
- Create Jetty environment XML
- Creates a
jetty-env.xmlfile for projects containing JBoss descriptor files.
- io.moderne.java.server.jboss.jetty.CreateJettyFilesInPath
- Migrate JBoss to Jetty
- Comprehensive migration from JBoss to Jetty.
- io.moderne.java.server.jboss.jetty.CreateJettySourceFile
- Create Jetty server source file
- Creates a
JettyServer.javasource file for projects containing JBoss descriptor files.
- io.moderne.java.server.jboss.jetty.MigrateJBossToJetty
- Migrate JBoss to Jetty
- Comprehensive migration from JBoss to Jetty.
- io.moderne.java.server.jboss.jetty.devcenter.JBossToJettyMigrationCard
- JBoss to Jetty migration
- Measures the progress of migrating applications from JBoss to Jetty. Analyzes the presence of JBoss descriptor files (jboss-web.xml, jboss-deployment-structure.xml) and Jetty jetty-env.xml configuration files to determine migration state.
- io.moderne.java.server.jboss.jetty.devcenter.JBossToJettyMigrationCard$Scanner
- JBoss to Jetty migration scanner
- Scans for JBoss and Jetty configuration files.
rewrite-kafka
- io.moderne.kafka.MigrateAdminListConsumerGroups
- Migrate
Admin.listConsumerGroups()tolistGroups() - Migrates the deprecated
Admin.listConsumerGroups()method tolistGroups()and updates related types for Kafka 4.1 compatibility.
- Migrate
- io.moderne.kafka.MigrateAlterConfigsToIncrementalAlterConfigs
- Migrate
AdminClient.alterConfigs()toincrementalAlterConfigs() - Migrates the removed
AdminClient.alterConfigs()method toincrementalAlterConfigs()for Kafka 4.0 compatibility.
- Migrate
- io.moderne.kafka.MigrateConsumerCommittedToSet
- Migrate
KafkaConsumer.committed(TopicPartition)tocommitted(Set<TopicPartition>) - Migrates from the removed
KafkaConsumer.committed(TopicPartition)tocommitted(Set<TopicPartition>)for Kafka 4.0 compatibility. Converts singleTopicPartitionarguments toCollections.singleton()calls.
- Migrate
- io.moderne.kafka.MigrateConsumerGroupStateToGroupState
- Migrate
ConsumerGroupStatetoGroupState - Migrates from the deprecated
ConsumerGroupStatetoGroupStatefor Kafka 4.0 compatibility.ConsumerGroupStatewas deprecated in favor ofGroupStatewhich supports both consumer groups and share groups.
- Migrate
- io.moderne.kafka.MigrateConsumerPollToDuration
- Migrate
KafkaConsumer.poll(long)topoll(Duration) - Migrates from the deprecated
KafkaConsumer.poll(long)topoll(Duration)for Kafka 4.0 compatibility. Converts millisecond timeout values toDuration.ofMillis()calls.
- Migrate
- io.moderne.kafka.MigrateSendOffsetsToTransaction
- Migrate deprecated
sendOffsetsToTransactionto useConsumerGroupMetadata - Migrates from the deprecated
KafkaProducer.sendOffsetsToTransaction(Map, String)tosendOffsetsToTransaction(Map, ConsumerGroupMetadata)for Kafka 4.0 compatibility. This recipe uses a conservative approach withnew ConsumerGroupMetadata(groupId).
- Migrate deprecated
- io.moderne.kafka.MigrateToKafka23
- Migrate to Kafka 2.3
- Migrate applications to the latest Kafka 2.3 release.
- io.moderne.kafka.MigrateToKafka24
- Migrate to Kafka 2.4
- Migrate applications to the latest Kafka 2.4 release.
- io.moderne.kafka.MigrateToKafka25
- Migrate to Kafka 2.5
- Migrate applications to the latest Kafka 2.5 release.
- io.moderne.kafka.MigrateToKafka26
- Migrate to Kafka 2.6
- Migrate applications to the latest Kafka 2.6 release.
- io.moderne.kafka.MigrateToKafka27
- Migrate to Kafka 2.7
- Migrate applications to the latest Kafka 2.7 release.
- io.moderne.kafka.MigrateToKafka28
- Migrate to Kafka 2.8
- Migrate applications to the latest Kafka 2.8 release.
- io.moderne.kafka.MigrateToKafka30
- Migrate to Kafka 3.0
- Migrate applications to the latest Kafka 3.0 release.
- io.moderne.kafka.MigrateToKafka31
- Migrate to Kafka 3.1
- Migrate applications to the latest Kafka 3.1 release.
- io.moderne.kafka.MigrateToKafka32
- Migrate to Kafka 3.2
- Migrate applications to the latest Kafka 3.2 release.
- io.moderne.kafka.MigrateToKafka33
- Migrate to Kafka 3.3
- Migrate applications to the latest Kafka 3.3 release.
- io.moderne.kafka.MigrateToKafka40
- Migrate to Kafka 4.0
- Migrate applications to the latest Kafka 4.0 release. This includes updating dependencies to 4.0.x, ensuring Java 11+ for clients and Java 17+ for brokers/tools, and handling changes.
- io.moderne.kafka.MigrateToKafka41
- Migrate to Kafka 4.1
- Migrate applications to the latest Kafka 4.1 release. This includes updating dependencies to 4.1.x, migrating deprecated Admin API methods, updating Streams configuration properties, and removing deprecated broker properties.
- io.moderne.kafka.RemoveDeprecatedKafkaProperties
- Remove deprecated Kafka property
- Removes a specific Kafka property that is no longer supported in Kafka 4.0.
- io.moderne.kafka.UpgradeJavaForKafkaBroker
- Upgrade Java to 17+ for Kafka broker/tools
- Ensures Java 17 or higher is used when Kafka broker or tools dependencies are present.
- io.moderne.kafka.UpgradeJavaForKafkaClients
- Upgrade Java to 11+ for Kafka clients
- Ensures Java 11 or higher is used when Kafka client libraries are present.
- io.moderne.kafka.streams.MigrateJoinedNameMethod
- Migrate
Joined.named()toJoined.as() - In Kafka Streams 2.3,
Joined.named()was deprecated in favor ofJoined.as(). Additionally, thename()method was deprecated for removal and should not be used.
- Migrate
- io.moderne.kafka.streams.MigrateKStreamToTable
- Migrate KStream to KTable conversion to use
toTable()method - In Kafka Streams 2.5, a new
toTable()method was added to simplify converting a KStream to a KTable. This recipe replaces the manual aggregation pattern.groupByKey().reduce((oldVal, newVal) -> newVal)with the more concise.toTable()method.
- Migrate KStream to KTable conversion to use
- io.moderne.kafka.streams.MigrateKafkaStreamsStoreMethod
- Migrate deprecated
KafkaStreams#storemethod - In Kafka Streams 2.5, the method
KafkaStreams#store(String storeName, QueryableStoreType<T> storeType)was deprecated. It only allowed querying active stores and did not support any additional query options. Use the newStoreQueryParametersAPI instead.
- Migrate deprecated
- io.moderne.kafka.streams.MigrateRetryConfiguration
- Migrate deprecated retry configuration to task timeout
- In Kafka 2.7,
RETRIES_CONFIGandRETRY_BACKOFF_MS_CONFIGwere deprecated in favor ofTASK_TIMEOUT_MS_CONFIG. This recipe migrates the old retry configuration to the new task timeout configuration, attempting to preserve the retry budget by multiplying retries × backoff time. If only one config is present, it falls back to 60000ms (1 minute).
- io.moderne.kafka.streams.MigrateStreamsUncaughtExceptionHandler
- Migrate to StreamsUncaughtExceptionHandler API
- Migrates from the JVM-level Thread.UncaughtExceptionHandler to Kafka Streams' StreamsUncaughtExceptionHandler API introduced in version 2.8. This new API provides explicit control over how the Streams client should respond to uncaught exceptions (REPLACE_THREAD, SHUTDOWN_CLIENT, or SHUTDOWN_APPLICATION).
- io.moderne.kafka.streams.MigrateTaskAndThreadMetadata
- Migrate TaskMetadata and ThreadMetadata
- Migrates TaskMetadata and ThreadMetadata from org.apache.kafka.streams.processor package to org.apache.kafka.streams package, and updates TaskMetadata.taskId() calls to include .toString() for String compatibility.
- io.moderne.kafka.streams.MigrateTaskMetadataTaskId
- Migrate
TaskMetadata.taskId()to returnTaskId - In Kafka Streams 3.0,
TaskMetadata.taskId()changed its return type fromStringtoTaskId. This recipe adds.toString()calls where necessary to maintain String compatibility.
- Migrate
- io.moderne.kafka.streams.MigrateWindowStorePutMethod
- Migrate
WindowStore.put()to include timestamp - In Kafka Streams 2.4,
WindowStore.put()requires a timestamp parameter. This recipe addscontext.timestamp()as the third parameter.
- Migrate
- io.moderne.kafka.streams.ProcessingGuaranteeExactlyOnceToBeta
- Migrate
exactly_oncetoexactly_once_beta - Kafka Streams 2.6 introduces the exactly-once semantics v2, which is a more efficient implementation with improved internal handling. Though it is beta, it’s fully backward-compatible from the API standpoint, but internally it uses a different transaction/commit protocol. Starting from 3.0, it becomes the default "exactly_once_v2".
- Migrate
- io.moderne.kafka.streams.ProcessingGuaranteeExactlyOnceToV2
- Migrate
exactly_onceandexactly_once_betatoexactly_once_v2 - Kafka Streams 2.6 introduces the exactly-once semantics v2, which is a more efficient implementation with improved internal handling. Starting from 3.0, it becomes the default "exactly_once_v2".
- Migrate
- io.moderne.kafka.streams.RemovePartitionGrouperConfiguration
- Remove
PartitionGrouperconfiguration - Starting with Kafka Streams 2.4, the
PartitionGrouperAPI was deprecated and partition grouping is now fully handled internally by the library. This recipe removes the deprecatedPARTITION_GROUPER_CLASS_CONFIGconfiguration.
- Remove
rewrite-prethink
- io.moderne.prethink.ComprehendCode
- Comprehend code with AI
- Use an LLM to generate descriptions for classes and methods in the codebase. Descriptions are cached based on source code checksums to avoid regenerating descriptions for unchanged code.
- io.moderne.prethink.ComprehendCodeTokenCounter
- Estimate comprehension token usage
- Estimate the input token counts that would be sent to an LLM for method comprehension, without actually calling a model. Uses OpenAI's tokenizer locally. Outputs to the MethodDescriptions table with blank descriptions.
- io.moderne.prethink.ExtractCodingConventions
- Extract coding conventions
- Analyze the codebase to extract coding conventions including naming patterns, import organization, and documentation patterns.
- io.moderne.prethink.ExtractDependencyUsage
- Extract dependency usage patterns
- Analyze the codebase to extract dependency usage patterns by examining which types from external libraries are actually used in the code.
- io.moderne.prethink.ExtractErrorPatterns
- Extract error handling patterns
- Analyze the codebase to extract error handling patterns including exception types, handling strategies, and logging frameworks used.
- io.moderne.prethink.UpdatePrethinkContextNoAiStarter
- Update Prethink context (no AI)
- Generate Moderne Prethink context files with architectural discovery, test coverage mapping, dependency inventory, and FINOS CALM architecture diagrams. This recipe does not require an LLM provider - use UpdatePrethinkContextStarter if you want AI-generated code comprehension and test summaries.
- io.moderne.prethink.UpdatePrethinkContextStarter
- Update Prethink context (with AI)
- Generate Moderne Prethink context files with AI-generated code comprehension, test coverage mapping, dependency inventory, and FINOS CALM architecture diagrams. Maps tests to implementation methods and optionally generates AI summaries of what each test verifies when LLM provider is configured.
- io.moderne.prethink.calm.FindCalmRelationships
- Find CALM relationships
- Discover method call relationships within the repository for building interaction diagrams. Captures all method-to-method calls between in-repo classes. Entity IDs are resolved by GenerateCalmArchitecture when building CALM relationships.
- io.moderne.prethink.calm.FindDataAssets
- Find data assets
- Identify data assets including JPA entities, MongoDB documents, Java records, and DTOs in the application.
- io.moderne.prethink.calm.FindDatabaseConnections
- Find database connections
- Identify database connections and data access patterns in the application. Detects JPA entities, Spring Data repositories, JDBC templates, MyBatis mappers, and Quarkus Panache.
- io.moderne.prethink.calm.FindDeploymentArtifacts
- Find deployment artifacts
- Identify deployment artifacts including Dockerfiles, docker-compose files, and Kubernetes manifests.
- io.moderne.prethink.calm.FindDjangoEndpoints
- Find Django endpoints
- Identify REST/HTTP endpoints in Django and Django REST Framework applications. Detects class-based views, function-based views with @api_view, and regular Django views with @require_http_methods decorators.
- io.moderne.prethink.calm.FindExpressEndpoints
- Find Express endpoints
- Identify REST/HTTP endpoints in Express and Fastify applications. Detects app.get(), router.post(), and similar route definition patterns.
- io.moderne.prethink.calm.FindExternalServiceCalls
- Find external service calls
- Identify outbound HTTP calls to external services. Detects RestTemplate, WebClient, Feign clients, MicroProfile REST Client, Apache HttpClient, OkHttp, and JAX-RS clients.
- io.moderne.prethink.calm.FindFastAPIEndpoints
- Find FastAPI endpoints
- Identify REST/HTTP endpoints in FastAPI applications. Detects @app.get(), @router.post(), and similar route decorator patterns.
- io.moderne.prethink.calm.FindFlaskEndpoints
- Find Flask endpoints
- Identify REST/HTTP endpoints in Flask applications. Detects @app.route(), @blueprint.route(), and Flask 2.0+ shortcut decorators like @app.get() and @app.post().
- io.moderne.prethink.calm.FindGraphQLEndpoints
- Find GraphQL endpoints
- Identify GraphQL endpoints exposed by the application. Supports Spring GraphQL, Netflix DGS, and GraphQL Java (graphql-java-tools).
- io.moderne.prethink.calm.FindGrpcServices
- Find gRPC services
- Identify gRPC service implementations in the application. Detects classes extending generated ImplBase classes and @GrpcService annotations.
- io.moderne.prethink.calm.FindMessagingConnections
- Find messaging connections
- Identify message queue producers and consumers. Detects Kafka, RabbitMQ, JMS, Spring Cloud Stream, AWS SQS, and SmallRye Reactive Messaging.
- io.moderne.prethink.calm.FindMongooseSchemas
- Find Mongoose schemas
- Identify Mongoose models and schemas in Node.js applications. Detects mongoose.model() calls and populates the DatabaseConnections table.
- io.moderne.prethink.calm.FindNestJSEndpoints
- Find NestJS endpoints
- Identify REST/HTTP endpoints in NestJS controllers. Detects @Controller, @Get, @Post, @Put, @Delete, and @Patch decorators and populates the ServiceEndpoints data table.
- io.moderne.prethink.calm.FindNodeErrorPatterns
- Find Node.js error patterns
- Identify error handling patterns in Node.js applications. Detects try/catch blocks and identifies logging frameworks used.
- io.moderne.prethink.calm.FindNodeHttpClients
- Find Node.js HTTP clients
- Identify HTTP client usage in Node.js applications. Detects axios, fetch, got, and superagent call patterns.
- io.moderne.prethink.calm.FindNodeMessaging
- Find Node.js messaging
- Identify messaging patterns in Node.js applications. Detects KafkaJS, amqplib, and Bull/BullMQ usage.
- io.moderne.prethink.calm.FindNodeProjectMetadata
- Find Node.js project metadata
- Extract project metadata (name, version, description) from Node.js package.json files.
- io.moderne.prethink.calm.FindNodeSecurityConfig
- Find Node.js security configuration
- Identify security middleware in Node.js applications. Detects cors, helmet, passport, and JWT middleware usage.
- io.moderne.prethink.calm.FindNodeTestCoverage
- Find Node.js test coverage
- Identify test methods in Jest, Mocha, and Vitest test files. Detects describe(), it(), and test() blocks and populates the TestMapping table.
- io.moderne.prethink.calm.FindPrismaUsage
- Find Prisma usage
- Identify Prisma ORM usage in Node.js applications. Detects prisma.model.findMany() and similar Prisma Client query patterns.
- io.moderne.prethink.calm.FindProjectMetadata
- Find project metadata
- Extract project metadata (artifact ID, group ID, name, description) from Maven pom.xml files.
- io.moderne.prethink.calm.FindPythonProjectMetadata
- Find Python project metadata
- Extract project metadata (name, version, description) from Python pyproject.toml files.
- io.moderne.prethink.calm.FindPythonTestCoverage
- Find Python test coverage
- Identify test methods in Python test files. Detects pytest test functions/classes and unittest.TestCase subclasses, and populates the TestMapping table.
- io.moderne.prethink.calm.FindSQLAlchemyModels
- Find SQLAlchemy and Django ORM models
- Identify ORM model classes in Python applications. Detects SQLAlchemy models with DeclarativeBase inheritance, Flask-SQLAlchemy models with db.Model, and Django ORM models extending models.Model.
- io.moderne.prethink.calm.FindScheduledTasks
- Find scheduled tasks
- Identify scheduled tasks and background jobs in the application. Supports Spring @Scheduled, Quarkus @Scheduled, Quartz Job, Jakarta/Javax EJB Timer, and JobRunr @Recurring annotations.
- io.moderne.prethink.calm.FindSecurityConfiguration
- Find security configuration
- Identify security configurations including Spring Security, OAuth2, CORS, Jakarta Security (@RolesAllowed, @PermitAll, @DenyAll), and Quarkus Security settings.
- io.moderne.prethink.calm.FindServerConfiguration
- Find server configuration
- Extract server configuration (port, SSL, context path) from application.properties and application.yml files.
- io.moderne.prethink.calm.FindServiceComponents
- Find service components
- Identify service layer components (@Service, @Component, @Named) in the application. Excludes controllers and repositories which are handled by dedicated recipes.
- io.moderne.prethink.calm.FindServiceEndpoints
- Find service endpoints
- Identify all REST/HTTP service endpoints exposed by the application. Supports Spring MVC, JAX-RS, Micronaut, and Quarkus REST endpoints.
- io.moderne.prethink.calm.FindTypeORMEntities
- Find TypeORM entities
- Identify TypeORM entities in Node.js applications. Detects @Entity() decorator on classes and populates the DatabaseConnections table.
- io.moderne.prethink.calm.FindWebSocketEndpoints
- Find WebSocket endpoints
- Identify WebSocket endpoints in the application. Supports Spring WebSocket, Spring STOMP messaging, and Jakarta/Javax WebSocket.
- io.moderne.prethink.calm.GenerateCalmMermaidDiagram
- Generate architecture mermaid diagram
- Generate a markdown file with a mermaid architecture diagram from discovered service endpoints, database connections, external service calls, and messaging connections.
- io.moderne.prethink.quality.FindClassMetrics
- Find class quality metrics
- Compute per-class code quality metrics including WMC, LCOM4, TCC, CBO, and maintainability index.
- io.moderne.prethink.quality.FindCodeSmells
- Find code smells
- Detect code smells including God Class, Feature Envy, and Data Class using composite metric thresholds with severity ratings.
- io.moderne.prethink.quality.FindMethodComplexity
- Find method complexity
- Compute per-method code quality metrics including cyclomatic complexity, cognitive complexity, max nesting depth, line count, parameter count, ABC metric, and Halstead measures.
- io.moderne.prethink.quality.FindPackageMetrics
- Find package quality metrics
- Compute per-package architectural quality metrics including afferent/efferent coupling, instability, abstractness, distance from the main sequence, and dependency cycle detection using Tarjan's strongly connected components algorithm.
- io.moderne.prethink.testing.coverage.FindTestCoverage
- Find test coverage mapping
- Map test methods to their corresponding implementation methods. Uses JavaType.Method matching to determine coverage relationships. Optionally generates AI summaries of what each test is verifying when LLM provider is configured.
- io.moderne.prethink.testing.coverage.FindTestGaps
- Find test coverage gaps
- Identify public non-trivial methods that lack test coverage. Reports gaps with cyclomatic complexity and risk scores to help prioritize where to add tests.
- io.moderne.prethink.testing.quality.FindFlakyTestPatterns
- Find flaky test patterns
- Detect patterns that commonly cause flaky tests in Java and Python code, including static waits (Thread.sleep, TimeUnit.sleep) and shared mutable state (static non-final fields in test classes).
- io.moderne.prethink.testing.quality.FindFragileTestData
- Find fragile test data
- Detect hardcoded dates, timing-dependent assertions, and hardcoded ports/paths in test code that may cause flaky or environment-dependent test failures.
- io.moderne.prethink.testing.quality.FindGhostTests
- Find ghost tests
- Detect methods that look like tests but will not be executed by the test runner, and tests skipped without a documented reason.
- io.moderne.prethink.testing.quality.FindNodeFlakyTestPatterns
- Find Node.js flaky test patterns
- Detect patterns that commonly cause flaky tests in JavaScript and TypeScript code, including static waits (setTimeout, setInterval), prototype mutation, and shared mutable state (module-scope let/var declarations).
- io.moderne.prethink.testing.quality.FindNodeFragileTestData
- Find Node.js fragile test data
- Detect hardcoded dates, timing-dependent assertions, and hardcoded ports in JavaScript and TypeScript test files.
- io.moderne.prethink.testing.quality.FindNodeGhostTests
- Find Node.js ghost tests
- Detect skipped tests in JavaScript and TypeScript test files. Flags xtest(), xit(), test.skip(), it.skip(), and describe.skip() calls that lack a documented reason in their description.
- io.moderne.prethink.testing.quality.FindNodeSilentTestFailures
- Find Node.js silent test failures
- Detect silent test failures in JavaScript and TypeScript test files including empty .catch() handlers and test functions missing expect() calls.
- io.moderne.prethink.testing.quality.FindNodeTestCodeSmells
- Find Node.js test code smells
- Detect code smells in JavaScript and TypeScript test files including empty catch blocks and magic numbers.
- io.moderne.prethink.testing.quality.FindNodeUnmockedExternalCalls
- Find unmocked external calls in Node.js tests
- Detect direct HTTP, database, and network calls in JavaScript/TypeScript test files that are not mocked. Integration and e2e test files are excluded.
- io.moderne.prethink.testing.quality.FindOverlyBroadMocks
- Find overly broad mocks
- Detect Mockito stubbing or verification calls that use 3 or more any() matchers, which can hide incorrect arguments and reduce test effectiveness.
- io.moderne.prethink.testing.quality.FindSilentTestFailures
- Find silent test failures
- Detect silent test failures including Java assert keyword usage, swallowed exceptions in try/catch blocks, and test methods missing assertions.
- io.moderne.prethink.testing.quality.FindTestCodeSmells
- Find test code smells
- Detect code smells in test files including empty catch blocks, deprecated test APIs, magic numbers, and poorly named test methods.
- io.moderne.prethink.testing.quality.FindUnmockedExternalCalls
- Find unmocked external calls in tests
- Detect direct HTTP, database, and network calls in unit tests that are not mocked. These cause flaky and slow tests. Integration tests (annotated with @SpringBootTest, @Testcontainers, etc.) are excluded.
rewrite-program-analysis
- io.moderne.recipe.rewrite-program-analysis.InlineDeprecatedMethods
- Inline deprecated delegating methods
- Automatically generated recipes to inline deprecated method calls that delegate to other methods in the same class.
- org.openrewrite.analysis.java.FindNullPointerIssues
- Find null pointer issues
- Detects potential null pointer dereferences using path-sensitive analysis to distinguish between definite NPEs, possible NPEs, and safe dereferences.
- org.openrewrite.analysis.java.controlflow.FindUnusedDefinitions
- Find unused variable definitions
- Identifies variable assignments whose values are never used before being overwritten.
- org.openrewrite.analysis.java.controlflow.search.FindCyclomaticComplexity
- Find cyclomatic complexity
- Calculates the cyclomatic complexity of methods and produces a data table containing the class name, method name, argument types, complexity value, and complexity threshold.
- org.openrewrite.analysis.java.controlflow.search.FindUnreachableCode
- Find unreachable code
- Uses control flow analysis to identify statements that can never be executed.
- org.openrewrite.analysis.java.dataflow.FindDeadStores
- Find dead stores
- Identifies variable assignments whose values are never used before being overwritten or going out of scope.
- org.openrewrite.analysis.java.dataflow.FindUnclosedResources
- Find unclosed resources (S2095)
- Identifies resources implementing AutoCloseable/Closeable that are opened but not properly closed on all execution paths. Unclosed resources can lead to resource leaks that degrade application performance and stability.
- org.openrewrite.analysis.java.datalineage.TrackDataLineage
- Track data lineage
- Tracks the flow of data from database sources to API sinks to understand data dependencies and support compliance requirements. ## Prerequisites for detecting a data flow All of the following conditions must be met for the recipe to report a flow: 1. The source code must contain at least one method call matching a recognized source (see below). 2. The source code must contain at least one method call matching a recognized sink (see below). 3. The tainted data must propagate from the source to the sink through variable assignments within the same method or via fields across methods in the same compilation unit. 4. No flow breaker (see below) may appear on the path between source and sink. 5. The relevant library types (e.g.,
java.sql.ResultSet,javax.ws.rs.core.Response) must be on the classpath so that OpenRewrite can resolve types. If types are unresolved, method matchers will not trigger and no flows will be detected. ## Recognized sources (database reads) | Category | Classes | | --- | --- | | JDBC |java.sql.ResultSet| | JPA (javax) |javax.persistence.EntityManager,Query,TypedQuery| | JPA (jakarta) |jakarta.persistence.EntityManager,Query,TypedQuery| | Hibernate |org.hibernate.Session,org.hibernate.query.Query| | Spring Data |org.springframework.data.repository.CrudRepository| | Spring JDBC |org.springframework.jdbc.core.JdbcTemplate| | MyBatis |org.apache.ibatis.session.SqlSession,org.mybatis.spring.SqlSessionTemplate| | MongoDB |com.mongodb.client.MongoCollection,org.springframework.data.mongodb.core.MongoTemplate| | Redis |redis.clients.jedis.Jedis,org.springframework.data.redis.core.RedisTemplate,ValueOperations,HashOperations| | Cassandra |com.datastax.driver.core.Session,org.springframework.data.cassandra.core.CassandraTemplate| | Elasticsearch |org.elasticsearch.client.RestHighLevelClient,org.springframework.data.elasticsearch.core.ElasticsearchTemplate| | Heuristic | Any class withRepository,Dao, orMapperin its name calling methods starting with find, get, query, search, load, fetch, or select | ## Recognized sinks (API responses) | Category | Classes | | --- | --- | | JAX-RS (javax) |javax.ws.rs.core.Response,Response.ResponseBuilder| | JAX-RS (jakarta) |jakarta.ws.rs.core.Response,Response.ResponseBuilder| | Spring MVC |org.springframework.http.ResponseEntity,ResponseEntity.BodyBuilder| | Servlet (javax) |javax.servlet.http.HttpServletResponse,javax.servlet.ServletOutputStream| | Servlet (jakarta) |jakarta.servlet.http.HttpServletResponse,jakarta.servlet.ServletOutputStream| | Java I/O |java.io.PrintWriter,java.io.Writer,java.io.OutputStream| | Jackson |com.fasterxml.jackson.databind.ObjectMapper,com.fasterxml.jackson.core.JsonGenerator| | Gson |com.google.gson.Gson,com.google.gson.JsonWriter| | GraphQL |graphql.schema.DataFetcher,graphql.schema.PropertyDataFetcher| | Spring WebFlux |ServerResponse,reactor.core.publisher.Mono,reactor.core.publisher.Flux| | gRPC |io.grpc.stub.StreamObserver| | WebSocket |javax.websocket.Session,RemoteEndpoint.Basic,jakarta.websocket.*,org.springframework.web.socket.WebSocketSession| ## Flow breakers Flows are broken by methods matching common sanitization patterns (anonymize, redact, mask, encrypt, hash, sanitize, etc.) or authorization checks (isAuthorized, hasPermission, hasRole, etc.).
- org.openrewrite.analysis.java.privacy.FindPiiExposure
- Find PII exposure in logs and external APIs
- Detects when Personally Identifiable Information (PII) is exposed through logging statements or sent to external APIs without proper sanitization. This helps prevent data leaks and ensures compliance with privacy regulations like GDPR and CCPA.
- org.openrewrite.analysis.java.security.FindArrayIndexInjection
- Find improper validation of array index
- Detects when user-controlled input flows into array or collection index expressions without proper bounds validation, which could allow out-of-bounds access or denial of service (CWE-129).
- org.openrewrite.analysis.java.security.FindCommandInjection
- Find command injection vulnerabilities
- Detects when user-controlled input flows into system command execution methods like Runtime.exec() or ProcessBuilder, which could allow attackers to execute arbitrary commands.
- org.openrewrite.analysis.java.security.FindJndiInjection
- Find JNDI injection vulnerabilities
- Detects when user-controlled input flows into JNDI lookup operations without proper validation, which could allow an attacker to connect to malicious naming/directory services (CWE-99).
- org.openrewrite.analysis.java.security.FindLdapInjection
- Find LDAP injection vulnerabilities
- Finds LDAP injection vulnerabilities by tracking tainted data flow from user input to LDAP queries.
- org.openrewrite.analysis.java.security.FindLogInjection
- Find log injection vulnerabilities
- Detects when user-controlled input flows into logging methods without sanitization, which could allow attackers to forge log entries by injecting newline characters.
- org.openrewrite.analysis.java.security.FindPathTraversal
- Find path traversal vulnerabilities
- Detects potential path traversal vulnerabilities where user input flows to file system operations without proper validation.
- org.openrewrite.analysis.java.security.FindProcessControlInjection
- Find process control vulnerabilities
- Detects when user-controlled input flows into native library loading methods without proper validation, which could allow an attacker to load arbitrary native code (CWE-114).
- org.openrewrite.analysis.java.security.FindSecurityVulnerabilities
- Find security vulnerabilities using taint analysis
- Identifies potential security vulnerabilities where untrusted data from sources flows to sensitive sinks without proper sanitization.
- org.openrewrite.analysis.java.security.FindSqlInjection
- Find SQL injection vulnerabilities
- Detects potential SQL injection vulnerabilities where user input flows to SQL execution methods without proper sanitization.
- org.openrewrite.analysis.java.security.FindUnencryptedPiiStorage
- Find unencrypted PII storage
- Identifies when personally identifiable information (PII) is stored in databases, files, or other persistent storage without encryption.
- org.openrewrite.analysis.java.security.FindUnsafeReflectionInjection
- Find unsafe reflection vulnerabilities
- Detects when user-controlled input flows into reflection-based class loading or instantiation without proper validation, which could allow an attacker to instantiate arbitrary classes (CWE-470).
- org.openrewrite.analysis.java.security.FindXssVulnerability
- Find XSS vulnerabilities
- Detects potential cross-site scripting vulnerabilities where user input flows to output methods without proper sanitization.
- org.openrewrite.analysis.java.security.FindXxeVulnerability
- Find XXE vulnerabilities
- Locates XML parsers that are not configured to prevent XML External Entity (XXE) attacks.
- org.openrewrite.analysis.java.security.SanitizeLogInjection
- Sanitize log injection vulnerabilities
- Sanitizes user-controlled input before it flows into logging methods by stripping newline, carriage return, and tab characters that could enable log forging.
rewrite-react
- org.openrewrite.react.search.FindPropUsage
- Find React prop usage
- Locates usages of a specific prop of a React component.
- org.openrewrite.react.search.FindReactComponent
- Find React component
- Locates usages of React components across the codebase including JSX elements and other references. If
componentNameisnull, finds all React components.
rewrite-release-metromap
- io.moderne.recipe.releasemetro.FindGradleParentRelationships
- Find Gradle project hierarchy relationships
- Find Gradle parent-child project relationships in multi-project builds to understand project hierarchies.
- io.moderne.recipe.releasemetro.FindGradleProjectIDs
- Find Gradle project IDs
- Find Gradle project IDs in build.gradle files to determine the project ID.
- io.moderne.recipe.releasemetro.FindMavenParentRelationships
- Find Maven parent relationships
- Find Maven parent POM relationships to understand project hierarchies in multi-module builds.
- io.moderne.recipe.releasemetro.FindMavenProjectIDs
- Find maven project IDs
- Find Maven group Id and artifactId in pom.xml files to determine the project ID.
- io.moderne.recipe.releasemetro.FindPotentiallyUnusedDependencies
- Find potentially unused dependencies
- Collects import information to help identify potentially unused dependencies.
- io.moderne.recipe.releasemetro.ReleaseMetroPlan
- Analyse Organization's Release Train Metro Plan
- Gathers the basic information to create and understand the organizations release train metro plan.
rewrite-spring
- io.moderne.java.jsf.MigrateToJsf_2_3
- Migrate to JSF 2.3
- Complete migration to JSF 2.3, including associated technologies like RichFaces. Updates dependencies, transforms XHTML views, and migrates Java APIs.
- io.moderne.java.jsf.richfaces.ConvertExtendedDataTableHeightToStyle
- Convert height/width attributes to
extendedDataTablestyle - Converts height and width attributes to inline style attribute for RichFaces
extendedDataTablecomponents.
- Convert height/width attributes to
- io.moderne.java.jsf.richfaces.MigrateRichFaces_4_5
- Migrate RichFaces 3.x to 4.5
- Complete RichFaces 3.x to 4.5 migration including tag renames, attribute migrations, and Java API updates.
- io.moderne.java.jsf.richfaces.update45.UpdateXHTMLTags
- Migrate RichFaces tags in
xhtmlfiles - Migrate RichFaces tags in
xhtmlfiles to RichFaces 4.
- Migrate RichFaces tags in
- io.moderne.java.spring.boot.AddSpringBootApplication
- Add
@SpringBootApplicationclass - Adds a
@SpringBootApplicationclass containing a main method to bootify your Spring Framework application.
- Add
- io.moderne.java.spring.boot.FieldToConstructorInjection
- Convert field injection to constructor injection
- Converts
@Autowiredfield injection to constructor injection pattern. For non-final classes, adds both a no-args constructor and the autowired constructor to maintain compatibility with extending classes. Moves@Qualifierannotations to constructor parameters.
- io.moderne.java.spring.boot.IsLikelyNotSpringBoot
- Is likely not a Spring Boot project
- Marks the project if it's likely not a Spring Boot project.
- io.moderne.java.spring.boot.IsLikelySpringBoot
- Is likely a Spring Boot project
- Marks the project if it's likely a Spring Boot project.
- io.moderne.java.spring.boot.MarkEmbeddedServerProvidedForWar
- Mark embedded server as provided for WAR projects
- For WAR-packaged projects migrating to Spring Boot, add the embedded Tomcat starter with provided scope to prevent conflicts with the external servlet container.
- io.moderne.java.spring.boot.MigrateSpringFrameworkDependenciesToSpringBoot
- Migrate Spring Framework dependencies to Spring Boot
- Migrate Spring Framework dependencies to Spring Boot.
- io.moderne.java.spring.boot.ReplaceSpringFrameworkDepsWithBootStarters
- Replace Spring Framework dependencies with Spring Boot starters
- Replace common Spring Framework dependencies with their Spring Boot starter equivalents. This recipe handles the direct dependency replacement; any remaining Spring Framework dependencies that become transitively available through starters are cleaned up separately by RemoveRedundantDependencies.
- io.moderne.java.spring.boot.SpringToSpringBoot
- Migrate Spring Framework to Spring Boot
- Migrate non Spring Boot applications to the latest compatible Spring Boot release. This recipe will modify an application's build files introducing Maven dependency management for Spring Boot, or adding the Gradle Spring Boot build plugin.
- io.moderne.java.spring.boot2.UpgradeSpringBoot_2_0
- Migrate to Spring Boot 2.0 (Moderne Edition)
- Migrate applications to the latest Spring Boot 2.0 release. This recipe will modify an application's build files, make changes to deprecated/preferred APIs, and migrate configuration settings that have changes between versions. This recipe will also chain additional framework migrations (Spring Framework, Spring Data, etc) that are required as part of the migration to Spring Boot 2.0.
- io.moderne.java.spring.boot3.AddValidToConfigurationPropertiesFields
- Add
@Validannotation to fields - In Spring Boot 3.4, validation of
@ConfigurationPropertiesclasses annotated with@Validatednow follows the Bean Validation specification, only cascading to nested properties if the corresponding field is annotated with@Valid. The recipe will add a@Validannotation to each field which has a type that has a field which is annotated with ajakarta.validation.constraints.*annotation.
- Add
- io.moderne.java.spring.boot3.CommentDeprecations
- Comment deprecated methods in Spring 3.4
- Spring Boot 3.4 deprecates methods that are not commonly used or need manual interaction.
- io.moderne.java.spring.boot3.CommentOnMockAndSpyBeansInConfigSpring34
- Comment on
@MockitoSpyBeanand@MockitoBeanin@Configuration - As stated in Spring Docs
@MockitoSpyBeanand@MockitoBeanwill only work in tests, explicitly not in@Configurationannotated classes.
- Comment on
- io.moderne.java.spring.boot3.ConditionalOnAvailableEndpointMigrationSpring34
- Migrate
ConditionalOnAvailableEndpointfor Spring Boot 3.4 - Migrate
@ConditionalOnAvailableEndpoint(EndpointExposure.CLOUD_FOUNDRY)to@ConditionalOnAvailableEndpoint(EndpointExposure.WEB)for Spring Boot 3.4.
- Migrate
- io.moderne.java.spring.boot3.MigrateAbstractDiscoveredEndpointConstructor
- Migrate
AbstractDiscoveredEndpointdeprecated constructor - The boolean-parameter constructor of
AbstractDiscoveredEndpointhas been deprecated in Spring Boot 3.4. This recipe transforms it to use the new constructor with anAccessparameter.
- Migrate
- io.moderne.java.spring.boot3.MigrateAbstractExposableEndpointConstructor
- Migrate
AbstractExposableEndpointdeprecated constructor - The boolean-parameter constructor of
AbstractExposableEndpointhas been deprecated in Spring Boot 3.4. This recipe transforms it to use the new constructor with anAccessparameter instead of booleanenableByDefault.
- Migrate
- io.moderne.java.spring.boot3.MigrateEndpointAnnotationAccessValueSpring34
- Migrate
@EndpointsdefaultAccessvalue - Since Spring Boot 3.4 the
@Endpointaccess configuration values are no longertrue|falsebutnone|read-only|unrestricted.
- Migrate
- io.moderne.java.spring.boot3.MigrateEndpointDiscovererConstructor
- Migrate
EndpointDiscovererdeprecated constructor - The 4-parameter constructor of
EndpointDiscovererhas been deprecated in Spring Boot 3.4. This recipe transforms it to use the new 5-parameter constructor with an additional Collection parameter.
- Migrate
- io.moderne.java.spring.boot3.MigrateEntityManagerFactoryBuilderConstructor
- Migrate
EntityManagerFactoryBuilderdeprecated constructor - The constructors of
EntityManagerFactoryBuilderhave been deprecated in Spring Boot 3.4. This recipe transforms them to use the new constructor with a Function parameter for property mapping.
- Migrate
- io.moderne.java.spring.boot3.MigrateJmxEndpointDiscovererConstructor
- Migrate
JmxEndpointDiscovererdeprecated constructor - The 4-parameter constructor of
JmxEndpointDiscovererhas been deprecated in Spring Boot 3.4. This recipe transforms it to use the new 5-parameter constructor with an additional Collection parameter.
- Migrate
- io.moderne.java.spring.boot3.MigrateRestTemplateToRestClient
- Migrate
RestTemplatetoRestClient - Migrates Spring's
RestTemplateto the modernRestClientAPI introduced in Spring Framework 6.1.RestClientprovides a fluent, synchronous API that is the recommended approach for new development. This recipe converts constructor calls, type declarations, and common method invocations (getForObject,getForEntity,postForObject,postForEntity,patchForObject,put,delete,headForHeaders,postForLocation,optionsForAllow,exchange) to theirRestClientequivalents.
- Migrate
- io.moderne.java.spring.boot3.MigrateWebEndpointDiscovererConstructor
- Migrate WebEndpointDiscoverer 6-parameter constructor to 8-parameter
- The 6-parameter constructor of
WebEndpointDiscovererhas been deprecated in Spring Boot 3.3. This recipe adds two new parameters (AdditionalPathsMapperandOperationFilter<WebOperation>) to the constructor and updates the Bean method signature to inject them asObjectProvidertypes.
- io.moderne.java.spring.boot3.RemoveDeprecatedConditions
- Remove Spring Boot 3.5 deprecated conditions
- Replace Spring Boot 3.5 deprecated condition classes with their corresponding conditional annotations.
- io.moderne.java.spring.boot3.RemoveReplaceNoneFromAutoConfigureTestDatabase
- Remove
Replace.NONEfrom@AutoConfigureTestDatabase Replace.NONEis the default value for@AutoConfigureTestDatabasesince Spring Boot 3.4.
- Remove
- io.moderne.java.spring.boot3.RemoveTestRestTemplateEnableRedirectsOptionRecipe
- Remove
TestRestTemplate.HttpClientOption.ENABLE_REDIRECTSoption - The
TestRestTemplatenow uses the same follow redirects settings as the regular RestTemplate. TheHttpOption.ENABLE_REDIRECTSoption has also been deprecated. This recipe removes the option from theTestRestTemplateconstructor arguments.
- Remove
- io.moderne.java.spring.boot3.ReplaceConditionalOutcomeInverse
- Replace ConditionOutcome.inverse() with constructor
- Replace deprecated
ConditionOutcome.inverse(ConditionOutcome outcome)calls withnew ConditionOutcome(!outcome.isMatch(), outcome.getConditionMessage()).
- io.moderne.java.spring.boot3.ReplaceDeprecatedKafkaConnectionDetailsBootstrapServerGetters
- Replace deprecated
KafkaConnectionDetailsbootstrap server methods - Replace deprecated
KafkaConnectionDetailsbootstrap server methods with chained calls. For example,getProducerBootstrapServers()becomesgetProducer().getBootstrapServers().
- Replace deprecated
- io.moderne.java.spring.boot3.ReplaceDeprecatedThreadPoolTaskSchedulerConstructor
- Replace deprecated ThreadPoolTaskSchedulerBuilder 5-argument constructor
- The 5-parameter constructor of
ThreadPoolTaskSchedulerBuilderhas been deprecated in Spring Boot 3.5. This recipe transforms it to use the builder pattern instead, omitting null values and defaults.
- io.moderne.java.spring.boot3.ReplaceKafkaTransactionManagerSetter
- Use
kafkaAwareTransactionManagersetter - Replace deprecated
ContainerProperties#setTransactionManager(org.springframework.transaction.PlatformTransactionManager)method withContainerProperties#setKafkaAwareTransactionManager(org.springframework.kafka.transaction.KafkaAwareTransactionManager). The method will be replaced only if its argument has the typeKafkaAwareTransactionManager.
- Use
- io.moderne.java.spring.boot3.ReplaceTaskExecutorNameByApplicationTaskExecutorName
- Use bean name
applicationTaskExecutorinstead oftaskExecutor - Spring Boot 3.5 removed the bean name
taskExecutor. Where this bean name is used, the recipe replaces the bean name toapplicationTaskExecutor. This also includes instances where the developer provided their own bean namedtaskExecutor. This also includes scenarios where JSR-250's@Resourceannotation is used.
- Use bean name
- io.moderne.java.spring.boot3.ResolveDeprecationsSpringBoot_3_3
- Resolve Deprecations in Spring Boot 3.3
- Migrates Deprecations in the Spring Boot 3.3 Release. Contains the removal of
DefaultJmsListenerContainerFactoryConfigurer.setObservationRegistryand adds new parameter ofWebEndpointDiscovererconstructor.
- io.moderne.java.spring.boot3.ResolveTaskExecutorFromContext
- Replace
taskExecutorwithapplicationTaskExecutor - Use bean name
applicationTaskExecutorinstead oftaskExecutorwhen resolvingTaskExecutorBean from application context.
- Replace
- io.moderne.java.spring.boot3.SpringBoot34Deprecations
- Migrate Spring Boot 3.4 deprecated classes and methods
- Migrate deprecated classes and methods that have been marked for removal in Spring Boot 4.0. This includes constructor changes for
EntityManagerFactoryBuilder,HikariCheckpointRestoreLifecycle, and various actuator endpoint discovery classes.
- io.moderne.java.spring.boot3.SpringBoot35Deprecations
- Migrate Spring Boot 3.5 deprecated classes and methods
- Migrate deprecated classes and methods that have been marked for removal in Spring Boot 3.5.
- io.moderne.java.spring.boot3.SpringBoot3BestPractices
- Spring Boot 3.5 best practices
- Applies best practices to Spring Boot 3.5+ applications.
- io.moderne.java.spring.boot3.SpringBootProperties_3_4
- Migrate
@EndpointSecurity properties to 3.4 (Moderne Edition) - Migrate the settings for Spring Boot Management Endpoint Security from
true|falsetoread-only|none.
- Migrate
- io.moderne.java.spring.boot3.UpdateOpenTelemetryResourceAttributes
- Update OpenTelemetry resource attributes
- The
service.groupresource attribute has been deprecated for OpenTelemetry in Spring Boot 3.5. Consider using alternative attributes or remove the deprecated attribute.
- io.moderne.java.spring.boot3.UpgradeGradle7Spring34
- Upgrade Gradle to 7.6.4+ for Spring Boot 3.4
- Spring Boot 3.4 requires Gradle 7.6.4.
- io.moderne.java.spring.boot3.UpgradeGradle8Spring34
- Upgrade Gradle 8 to 8.4+ for Spring Boot 3.4
- Spring Boot 3.4 requires Gradle 8.4+.
- io.moderne.java.spring.boot3.UpgradeMyBatisToSpringBoot_3_4
- Upgrade MyBatis to Spring Boot 3.4
- Upgrade MyBatis Spring modules to a version corresponding to Spring Boot 3.4.
- io.moderne.java.spring.boot3.UpgradeMyBatisToSpringBoot_3_5
- Upgrade MyBatis to Spring Boot 3.5
- Upgrade MyBatis Spring modules to a version corresponding to Spring Boot 3.5.
- io.moderne.java.spring.boot3.UpgradeSpringBoot_3_4
- Migrate to Spring Boot 3.4 (Moderne Edition)
- Migrate applications to the latest Spring Boot 3.4 release. This recipe will modify an application's build files, make changes to deprecated/preferred APIs, and migrate configuration settings that have changes between versions. This recipe will also chain additional framework migrations (Spring Framework, Spring Data, etc) that are required as part of the migration to Spring Boot 3.4.
- io.moderne.java.spring.boot3.UpgradeSpringBoot_3_5
- Migrate to Spring Boot 3.5 (Moderne Edition)
- Migrate applications to the latest Spring Boot 3.5 release. This recipe will modify an application's build files, make changes to deprecated/preferred APIs, and migrate configuration settings that have changes between versions. This recipe will also chain additional framework migrations (Spring Framework, Spring Data, etc) that are required as part of the migration to Spring Boot 3.5.
- io.moderne.java.spring.boot3.UpgradeSpringCloudAWSToSpringBoot_3_4
- Upgrade Spring Cloud AWS to Spring Boot 3.4 compatible version
- Upgrade the Spring Cloud AWS dependency to a version compatible with Spring Boot 3.4.
- io.moderne.java.spring.boot3.UpgradeSpringKafka_3_3
- Migrate to Spring Kafka 3.3
- Migrate applications to the latest Spring Kafka 3.3 release.
- io.moderne.java.spring.boot4.AddAutoConfigureMockMvc
- Add
@AutoConfigureMockMvcto@SpringBootTestclasses usingMockMvc - Adds
@AutoConfigureMockMvcannotation to classes annotated with@SpringBootTestthat useMockMvc.
- Add
- io.moderne.java.spring.boot4.AddFlywayStarters
- Add Flyway starters
- Adds spring-boot-starter-flyway and spring-boot-starter-flyway-test dependencies when Flyway usage is detected in the module.
- io.moderne.java.spring.boot4.AddJackson2ForJerseyJson
- Add Jackson2 for Jersey using JSON
- Check whether a module uses Jersey on combination with JSON and adds the needed
spring-boot-jacksondependency and conditionallyspring-boot-jackson2dependency.
- io.moderne.java.spring.boot4.AddLenientMockitoSettings
- Add
@MockitoSettings(strictness = Strictness.LENIENT)for@MockitoBeantests - When migrating from
@MockBeanto@MockitoBean, the implicit LENIENT Mockito strictness from Spring Boot'sMockitoPostProcessoris lost. If@ExtendWith(MockitoExtension.class)is present, Mockito enforces STRICT_STUBS by default, causingUnnecessaryStubbingExceptionfor tests with unused stubs. This recipe adds@MockitoSettings(strictness = Strictness.LENIENT)to preserve the original behavior.
- Add
- io.moderne.java.spring.boot4.AddLiquibaseStarters
- Add Liquibase starters
- Adds spring-boot-starter-liquibase and spring-boot-starter-liquibase-test dependencies when Liquibase usage is detected in the module.
- io.moderne.java.spring.boot4.AddModularStarters
- Add Spring Boot 4.0 modular starters
- Add Spring Boot 4.0 starter dependencies based on package usage. Note: Higher-level starters (like data-jpa) include lower-level ones (like jdbc) transitively, so only the highest-level detected starter is added for each technology.
- io.moderne.java.spring.boot4.AddMongoDbRepresentationProperties
- Add MongoDB representation properties for UUID and BigDecimal
- Adds the 'spring.mongodb.representation.uuid' property with value 'standard' and the 'spring.data.mongodb.representation.big-decimal' property with the value 'decimal128' to Spring configuration files when a MongoDB dependency is detected.
- io.moderne.java.spring.boot4.AddMssqlKerberosJaasConfig
- Add
useDefaultJaasConfig=trueto MSSQL Kerberos JDBC URLs - For MSSQL JDBC connections using Kerberos authentication (
authenticationScheme=JavaKerberosorintegratedSecurity=true), addsuseDefaultJaasConfig=trueto the connection string. This is required for compatibility with Keycloak 26.4+ which changes JAAS configuration handling.
- Add
- io.moderne.java.spring.boot4.AddValidationStarterDependency
- Add
spring-boot-starter-validationdependency - In Spring Boot 4, validation is no longer auto-included from the web starter. This recipe adds the
spring-boot-starter-validationdependency when Jakarta Validation annotations are used in the project.
- Add
- io.moderne.java.spring.boot4.AdoptJackson3
- Adopt Jackson 3
- Adopt Jackson 3 which is supported by Spring Boot 4 and Jackson 2 support is deprecated.
- io.moderne.java.spring.boot4.FlagDeprecatedReactorNettyHttpClientMapper
- Flag deprecated ReactorNettyHttpClientMapper for migration
- Adds a TODO comment to classes implementing the deprecated
ReactorNettyHttpClientMapperinterface. Migration toClientHttpConnectorBuilderCustomizer<ReactorClientHttpConnectorBuilder>requires wrapping the HttpClient configuration inbuilder.withHttpClientCustomizer(...).
- io.moderne.java.spring.boot4.InsertPropertyMapperAlwaysMethodInvocation
- Preserve
PropertyMappernull-passing behavior - Spring Boot 4.0 changes the
PropertyMapperbehavior so thatfrom()no longer callsto()when the source value isnull. This recipe inserts.always()before terminal mapping methods to preserve the previous behavior. Chains that already contain.whenNonNull()or.alwaysApplyingWhenNonNull()are skipped, as they explicitly opted into null-skipping behavior which is now the default.
- Preserve
- io.moderne.java.spring.boot4.MigrateHazelcastSpringSession
- Migrate Spring Session Hazelcast to Hazelcast Spring Session
- Spring Boot 4.0 removed direct support for Spring Session Hazelcast. The Hazelcast team now maintains their own Spring Session integration. This recipe changes the dependency from
org.springframework.session:spring-session-hazelcasttocom.hazelcast.spring:hazelcast-spring-sessionand updates the package fromorg.springframework.session.hazelcasttocom.hazelcast.spring.session.
- io.moderne.java.spring.boot4.MigrateMockMvcToAssertJ
- Migrate MockMvc to AssertJ assertions
- Migrates Spring MockMvc tests from Hamcrest-style
andExpect()assertions to AssertJ-style fluent assertions. ChangesMockMvctoMockMvcTesterand converts assertion chains.
- io.moderne.java.spring.boot4.MigratePropertyMapper
- Migrate
PropertyMapperAPI for Spring Boot 4.0 - Migrates
PropertyMapperusage to accommodate Spring Boot 4.0 behavioral changes. In Boot 4.0,PropertyMapper.from()no longer callsto()when the source value isnull. This recipe first inserts.always()on bare chains to preserve null-passing behavior, then removes the now-redundant.whenNonNull()and.alwaysApplyingWhenNonNull()calls. Guarded by a Spring Boot < 4.0 precondition so that on subsequent recipe cycles (after the version is bumped by the parent migration recipe), this recipe becomes a no-op — preventing it from incorrectly adding.always()to chains that just had.whenNonNull()stripped.
- Migrate
- io.moderne.java.spring.boot4.MigrateRestAssured
- Add explicit version for REST Assured
- REST Assured is no longer managed by Spring Boot 4.0. This recipe adds an explicit version to REST Assured dependencies.
- io.moderne.java.spring.boot4.MigrateSpringRetry
- Migrate Spring Retry to Spring Resilience
- Handle spring-retry no longer managed by Spring Boot and the possible migration to Spring Core Resilience.
- io.moderne.java.spring.boot4.MigrateSpringRetryToSpringFramework7
- Migrate
spring-retryto Spring Framework resilience - Migrate
spring-retrys@Retryableand@Backoffannotation to Spring Framework 7 Resilience annotations.
- Migrate
- io.moderne.java.spring.boot4.MigrateToModularStarters
- Migrate to Spring Boot 4.0 modular starters (Moderne Edition)
- Remove monolithic starters and adds the necessary Spring Boot 4.0 starter dependencies based on package usage, where any spring-boot-starter was used previously.
- io.moderne.java.spring.boot4.MockMvcAssertionsToAssertJ
- Migrate MockMvc
andExpect()chains to AssertJ assertions - Converts MockMvc Hamcrest-style
andExpect()assertion chains to AssertJ-style fluent assertions usingassertThat(). Handles status, content, JSON path, header, redirect, and forward assertions.
- Migrate MockMvc
- io.moderne.java.spring.boot4.MockMvcRequestBuildersToMockMvcTester
- Migrate
MockMvcRequestBuilderstoMockMvcTesterrequest methods - Converts
mockMvcTester.perform(get("/api").param("k","v"))tomockMvcTester.get().uri("/api").param("k","v"), removing theperform()wrapper andMockMvcRequestBuildersstatic method calls.
- Migrate
- io.moderne.java.spring.boot4.MockMvcToMockMvcTester
- Migrate
MockMvctoMockMvcTester - Converts
MockMvcfields and initialization toMockMvcTester. Changes field types, renames fields frommockMvctomockMvcTester, and convertsMockMvcBuilders.standaloneSetup().build()toMockMvcTester.of()andMockMvcBuilders.webAppContextSetup().build()toMockMvcTester.from().
- Migrate
- io.moderne.java.spring.boot4.ModuleHasMonolithicStarter
- Module has monolithic Spring Boot starter
- Precondition that matches modules with the monolithic Spring Boot starters that need to be migrated to modular starters. Matches the production monolithic spring-boot-starter and spring-boot-starter-classic, but not specific modular starters like spring-boot-starter-test or spring-boot-starter-ldap.
- io.moderne.java.spring.boot4.ModuleStarterRelocations
- Spring Boot 4.0 Module Starter Relocations
- Relocate types and packages for Spring Boot 4.0 modular starters.
- io.moderne.java.spring.boot4.ModuleUsesFlyway
- Module uses Flyway
- Precondition that marks all files in a module if Flyway usage is detected. Detection is based on having a Flyway dependency, using Flyway types, or having migration files.
- io.moderne.java.spring.boot4.ModuleUsesLiquibase
- Module uses Liquibase
- Precondition that marks all files in a module if Liquibase usage is detected. Detection is based on having a Liquibase dependency, using Liquibase types, or having changelog files.
- io.moderne.java.spring.boot4.RemoveContentNegotiationFavorPathExtension
- Remove
ContentNegotiationConfigurer.favorPathExtension()calls - Spring Framework 7 removed
favorPathExtension()fromContentNegotiationConfigurer. Path extension content negotiation is no longer supported. This recipe removes calls tofavorPathExtension().
- Remove
- io.moderne.java.spring.boot4.RemoveGradleUberJarLoaderImplementationConfig
- Remove
loaderImplementationfrom Gradle - Removes the Spring Boot Uber-Jar
loaderImplementationconfiguration from Gradle build files.
- Remove
- io.moderne.java.spring.boot4.RemoveHttpMessageConvertersAutoConfigurationReferences
- Remove
HttpMessageConvertersAutoConfigurationreferences - Removes references to the deprecated
HttpMessageConvertersAutoConfigurationclass which was removed in Spring Boot 4.0. For@AutoConfigureAfterand@AutoConfigureBeforeannotations, the reference is removed. For@Importannotations, a TODO comment is added since manual migration may be required.
- Remove
- io.moderne.java.spring.boot4.RemoveKafkaPropertiesSslBundlesParameter
- Remove
SslBundlesparameter fromKafkaPropertiesbuild methods - In Spring Boot 4.0, the
SslBundlesparameter was removed fromKafkaProperties.buildProducerProperties,buildConsumerProperties,buildAdminProperties, andbuildStreamsProperties. This recipe removes the argument from method calls.
- Remove
- io.moderne.java.spring.boot4.RemoveSpringPulsarReactive
- Remove Spring Pulsar Reactive support
- Spring Boot 4.0 removed support for Spring Pulsar Reactive as it is no longer maintained. This recipe removes the Spring Pulsar Reactive dependencies.
- io.moderne.java.spring.boot4.RemoveZipkinAutoConfigurationExclude
- Remove
ZipkinAutoConfiguration - Zipkin is no longer auto-configured by default in Spring Boot 4.0; remove references to it from exclusions on annotations.
- Remove
- io.moderne.java.spring.boot4.ReplaceDeprecatedAutoconfigureMongoApi
- Replace deprecated
org.springframework.boot.autoconfigure.mongoAPI - Replace deprecated
org.springframework.boot.autoconfigure.mongoAPI.
- Replace deprecated
- io.moderne.java.spring.boot4.ReplaceDeprecatedDockerApi
- Replace deprecated
DockerApi - Replaces deprecated
DockerApiconstructors and configuration methods with their modern equivalents.
- Replace deprecated
- io.moderne.java.spring.boot4.ReplaceDeprecatedRequestMatcherProvider
- Replace deprecated RequestMatcherProvider with new API
- Replaces the deprecated
org.springframework.boot.autoconfigure.security.servlet.RequestMatcherProviderwithorg.springframework.boot.security.autoconfigure.actuate.web.servlet.RequestMatcherProvider. The new interface adds anHttpMethodparameter to thegetRequestMatchermethod.
- io.moderne.java.spring.boot4.ReplaceDeprecatedThreadPoolTaskSchedulerBuilderApi
- Replace deprecated
ThreadPoolTaskSchedulerBuilderconstructor - Replaces the deprecated 5-argument constructor of
ThreadPoolTaskSchedulerBuilderwith the builder pattern.
- Replace deprecated
- io.moderne.java.spring.boot4.SpringBoot4BestPractices
- Spring Boot 4.0 best practices
- Applies best practices to Spring Boot 4.+ applications.
- io.moderne.java.spring.boot4.UpgradeMyBatisToSpringBoot_4_0
- Upgrade MyBatis to Spring Boot 4.0
- Upgrade MyBatis Spring modules to a version corresponding to Spring Boot 4.0.
- io.moderne.java.spring.boot4.UpgradeSpringBoot_4_0
- Migrate to Spring Boot 4.0 (Moderne Edition)
- Migrate applications to the latest Spring Boot 4.0 release. This recipe will modify an application's build files, make changes to deprecated/preferred APIs, and migrate configuration settings that have changes between versions. This recipe will also chain additional framework migrations (Spring Framework, Spring Data, etc) that are required as part of the migration to Spring Boot 4.0.
- io.moderne.java.spring.boot4.UpgradeSpringKafka_4_0
- Migrate to Spring Kafka 4.0
- Migrate applications to Spring Kafka 4.0. This includes removing deprecated configuration options that are no longer supported.
- io.moderne.java.spring.cloud2020.SpringCloudProperties_2020
- Migrate Spring Cloud properties to 2020
- Migrate properties found in
application.propertiesandapplication.yml.
- io.moderne.java.spring.cloud2021.SpringCloudProperties_2021
- Migrate Spring Cloud properties to 2021
- Migrate properties found in
application.propertiesandapplication.yml.
- io.moderne.java.spring.cloud2022.SpringCloudProperties_2022
- Migrate Spring Cloud properties to 2022
- Migrate properties found in
application.propertiesandapplication.yml.
- io.moderne.java.spring.cloud2023.SpringCloudProperties_2023
- Migrate Spring Cloud properties to 2023
- Migrate properties found in
application.propertiesandapplication.yml.
- io.moderne.java.spring.cloud2024.SpringCloudProperties_2024
- Migrate Spring Cloud properties to 2024
- Migrate properties found in
application.propertiesandapplication.yml.
- io.moderne.java.spring.cloud2025.SpringCloudProperties_2025
- Migrate Spring Cloud properties to 2025
- Migrate properties found in
application.propertiesandapplication.yml.
- io.moderne.java.spring.cloud20251.SpringCloudProperties_2025_1
- Migrate Spring Cloud properties to 2025.1
- Migrate properties found in
application.propertiesandapplication.ymlfor Spring Cloud 2025.1 (Oakwood). This includes the stubrunner property prefix migration fromstubrunner.tospring.cloud.contract.stubrunner..
- io.moderne.java.spring.cloud20251.UpgradeSpringCloud_2025_1
- Upgrade to Spring Cloud 2025.1
- Upgrade to Spring Cloud 2025.1 (Oakwood). This release is based on Spring Framework 7 and Spring Boot 4. Each Spring Cloud project has been updated to version 5.0.0.
- io.moderne.java.spring.framework.AddSetUseSuffixPatternMatch
- Add
setUseSuffixPatternMatch(true)in Spring MVC configuration - In Spring Framework 5.2.4 and earlier, suffix pattern matching was enabled by default. This meant a controller method mapped to
/userswould also match/users.json,/users.xml, etc. Spring Framework 5.3 deprecated this behavior and changed the default to false. This recipe addssetUseSuffixPatternMatch(true)toWebMvcConfigurerimplementations to preserve the legacy behavior during migration. Note: This only applies to Spring MVC; Spring WebFlux does not support suffix pattern matching.
- Add
- io.moderne.java.spring.framework.AddSetUseSuffixPatternMatchIfPreSpring53
- Add
setUseSuffixPatternMatch(true)for pre-Spring Framework 5.3 projects - Only adds
setUseSuffixPatternMatch(true)when the project is on Spring Framework < 5.3, where suffix pattern matching was enabled by default. Projects already on 5.3+ have been running with the new default (false) and should not get this configuration added.
- Add
- io.moderne.java.spring.framework.FindDeprecatedPathMatcherUsage
- Find deprecated
PathMatcherusage - In Spring Framework 7.0,
PathMatcherandAntPathMatcherare deprecated in favor ofPathPatternParser. This recipe finds usages of the deprecatedAntPathMatcherclass that may require manual migration toPathPatternParser.
- Find deprecated
- io.moderne.java.spring.framework.FlagSuffixPatternMatchUsage
- Flag deprecated suffix pattern matching usage for manual review
- Handles deprecated
setUseSuffixPatternMatch()andsetUseRegisteredSuffixPatternMatch()calls. When suffix pattern matching is explicitly enabled, adds TODO comments and search markers since there is no automatic migration path. When explicitly disabled, the call is safely removed sincefalseis already the default since Spring Framework 5.3.
- io.moderne.java.spring.framework.IsLikelySpringFramework
- Is likely a Spring Framework project
- Marks the project if it's likely a Spring Framework project.
- io.moderne.java.spring.framework.JaxRsToSpringWeb
- Convert JAX-RS annotations to Spring Web
- Converts JAX-RS annotations such as
@Path,@GET,@POST, etc., to their Spring Web equivalents like@RestController,@RequestMapping,@GetMapping, etc.
- io.moderne.java.spring.framework.MigrateConverterSetObjectMapper
- Replace
setObjectMapperwith constructor injection - Folds
setObjectMappercalls onMappingJackson2HttpMessageConverterinto the constructor. If the converter is instantiated in the same block with no other invocations, the setter call is replaced with constructor injection. Otherwise, a TODO comment is added.
- Replace
- io.moderne.java.spring.framework.MigrateDefaultResponseErrorHandler
- Migrate
DefaultResponseErrorHandler.handleErrormethod signature - Migrates overridden
handleError(ClientHttpResponse response)methods to the new signaturehandleError(URI url, HttpMethod method, ClientHttpResponse response)in classes extendingDefaultResponseErrorHandler. The old single-argument method was removed in Spring Framework 7.0.
- Migrate
- io.moderne.java.spring.framework.MigrateDeprecatedBeanXmlProperties
- Migrate Bean XML properties deprecated in Spring Framework 3.0
- Migrate Bean XML properties that were deprecated in Spring Framework 3.0.
- io.moderne.java.spring.framework.MigrateFilterToOncePerRequestFilter
- Migrate
FiltertoOncePerRequestFilter - Migrates classes that implement
javax.servlet.Filter(orjakarta.servlet.Filter) to extendorg.springframework.web.filter.OncePerRequestFilter. This transformation renamesdoFiltertodoFilterInternal, changes parameter types to HTTP variants, removes manual casting, and removes emptyinit()anddestroy()methods.
- Migrate
- io.moderne.java.spring.framework.MigrateHandleErrorMethodInvocations
- Migrate
handleErrormethod invocations to new signature - Updates invocations of
handleError(ClientHttpResponse)to the newhandleError(URI, HttpMethod, ClientHttpResponse)signature introduced in Spring Framework 7.0. In test sources, example values are used. In main sources,nullis passed with a TODO comment.
- Migrate
- io.moderne.java.spring.framework.MigrateHttpHeadersMultiValueMapMethods
- Migrate
HttpHeadersmethods removed whenMultiValueMapcontract was dropped - Spring Framework 7.0 changed
HttpHeadersto no longer implementMultiValueMap. This recipe replaces removed inherited method calls:containsKey()withcontainsHeader(),keySet()withheaderNames(), andentrySet()withheaderSet().
- Migrate
- io.moderne.java.spring.framework.MigrateTrailingSlashMatch
- Migrate trailing slash matching to explicit routes
- Migrates deprecated
setUseTrailingSlashMatch()configuration removed in Spring Framework 7.0. Only adds explicit trailing slash routes when the project previously enabled trailing slash matching viasetUseTrailingSlashMatch(true). The deprecated configuration calls are always removed.
- io.moderne.java.spring.framework.ModularSpringFrameworkDependencies
- Add Spring Framework modular dependencies
- Adds Spring Framework modular dependencies based on package usage, replacing legacy monolithic
org.springframework:spring.
- io.moderne.java.spring.framework.NullableSpringWebParameters
- Add
@Nullableto optional Spring web parameters - In Spring Boot 4, JSpecify's
@Nullableannotation should be used to indicate that a parameter can be null. This recipe adds@Nullableto parameters annotated with@PathVariable(required = false)or@RequestParam(required = false)and removes the now-redundantrequired = falseattribute.
- Add
- io.moderne.java.spring.framework.RemoveDeprecatedPathMappingOptions
- Migrate deprecated path mapping options
- Migrates deprecated path mapping configuration options that have been removed in Spring Framework 7.0. For trailing slash matching, this recipe adds explicit dual routes to controller methods before removing the deprecated configuration. For suffix pattern matching, this recipe flags usages for manual review since there is no automatic migration path. Path extension content negotiation options are removed as they should be replaced with query parameter-based negotiation.
- io.moderne.java.spring.framework.RemoveEmptyPathMatchConfiguration
- Remove empty path match configuration methods
- Removes empty
configurePathMatch(WebMvc) andconfigurePathMatching(WebFlux) method overrides. These methods may become empty after deprecated path matching options are removed.
- io.moderne.java.spring.framework.RemovePathExtensionContentNegotiation
- Remove path extension content negotiation methods
- Remove calls to
favorPathExtension()andignoreUnknownPathExtensions()onContentNegotiationConfigurer. These methods and the underlyingPathExtensionContentNegotiationStrategywere removed in Spring Framework 7.0. Path extension content negotiation was deprecated due to URI handling issues. Use query parameter-based negotiation withfavorParameter(true)as an alternative.
- io.moderne.java.spring.framework.RemoveSetPathMatcherCall
- Remove deprecated
setPathMatcher()calls - In Spring Framework 7.0,
PathMatcherandAntPathMatcherare deprecated in favor ofPathPatternParser, which has been the default in Spring MVC since 6.0. This recipe removes calls tosetPathMatcher(new AntPathMatcher())since they are now redundant. The defaultPathPatternParserprovides better performance through pre-parsed patterns.
- Remove deprecated
- io.moderne.java.spring.framework.ReplaceControllerWithRestController
- Replace
@Controllerwith@RestController - When a class is annotated with
@Controllerand either the class itself or all of its handler methods are annotated with@ResponseBody, the class can use@RestControllerinstead. This removes the need for individual@ResponseBodyannotations.
- Replace
- io.moderne.java.spring.framework.UpgradeSpringFramework_3_0
- Migrate to Spring Framework 3.x
- Migrate applications to the latest Spring Framework 3 release, pulling in additional proprietary Moderne recipes.
- io.moderne.java.spring.framework.UpgradeSpringFramework_5_3
- Migrate to Spring Framework 5.3 (Moderne Edition)
- Migrate applications to the latest Spring Framework 5.3 release, pulling in additional proprietary Moderne recipes.
- io.moderne.java.spring.framework.beansxml.BeansXmlToConfiguration
- Migrate
beans.xmlto Spring Framework configuration class - Converts Java/Jakarta EE
beans.xmlconfiguration files to Spring Framework@Configurationclasses.
- Migrate
- io.moderne.java.spring.framework.jsf23.MigrateFacesConfig
- Migrate JSF variable-resolver to el-resolver
- Migrates JSF faces-config.xml from namespaces, tags and values that was deprecated in JSF 1.2 and removed in later versions, to the JSF 2.3 compatible constructs.
- io.moderne.java.spring.framework.webxml.FindWelcomeFileConfiguration
- Add landing page controller for welcome file configuration
- Generates a
LandingPageControllerwhenwelcome-file-listis found inweb.xmlorcontext-rootinjboss-web.xml. When migrating to Spring Framework 5.3+, applications that rely on these server-side landing page configurations need a@Controllerwith a@RequestMappingfor/to avoid 404 errors, as Spring MVC can take over the root mapping. Skips generation if a controller already maps to/.
- io.moderne.java.spring.framework.webxml.WebXmlToWebApplicationInitializer
- Migrate
web.xmltoWebApplicationInitializer - Migrate
web.xmltoWebApplicationInitializerfor Spring applications. This allows for programmatic configuration of the web application context, replacing the need for XML-based configuration. This recipe only picks upweb.xmlfiles located in thesrc/main/webapp/WEB-INFdirectory to avoid inference with tests. It creates aWebXmlWebAppInitializerclass insrc/main/javawith respect to submodules if they contain java files. If it finds an existingWebXmlWebAppInitializer, it skips the creation.
- Migrate
- io.moderne.java.spring.framework7.AddDynamicDestinationResolverToJmsTemplate
- Explicitly set DynamicDestinationResolver on JmsTemplate
- Spring Framework 7.0 changed the default
DestinationResolverforJmsTemplatefromDynamicDestinationResolvertoSimpleDestinationResolver, which caches Session-resolved Queue and Topic instances. This recipe adds an explicit call tosetDestinationResolver(new DynamicDestinationResolver())to preserve the previous behavior. The caching behavior ofSimpleDestinationResolvershould be fine for most JMS brokers, so this explicit configuration can be removed once compatibility with the new default is verified.
- io.moderne.java.spring.framework7.AddSpringExtensionConfigForNestedTests
- Add
@SpringExtensionConfigfor nested tests - Spring Framework 7.0 changed
SpringExtensionto use test-method scopedExtensionContextinstead of test-class scoped. This can break@Nestedtest class hierarchies. Adding@SpringExtensionConfig(useTestClassScopedExtensionContext = true)restores the previous behavior.
- Add
- io.moderne.java.spring.framework7.FindOkHttp3IntegrationUsage
- Find Spring OkHttp3 integration usage
- Spring Framework 7.0 removes OkHttp3 integration classes. This recipe identifies usages of
OkHttp3ClientHttpRequestFactoryandOkHttp3ClientHttpConnectorthat need to be replaced. Consider migrating to Java's built-inHttpClientwithJdkClientHttpRequestFactoryorJdkClientHttpConnector, or to Apache HttpClient 5 withHttpComponentsClientHttpRequestFactory.
- io.moderne.java.spring.framework7.FindRemovedAPIs
- Find removed APIs in Spring Framework 7.0
- Finds usages of APIs that were removed in Spring Framework 7.0 and require manual intervention. This includes Theme support, OkHttp3 integration, and servlet view document/feed classes which have no direct automated replacement.
- io.moderne.java.spring.framework7.FindServletViewSupportUsage
- Find removed Spring servlet view classes
- Spring Framework 7.0 removes the
org.springframework.web.servlet.view.documentandorg.springframework.web.servlet.view.feedpackages. This recipe adds TODO comments to imports ofAbstractPdfView,AbstractXlsView,AbstractXlsxView,AbstractXlsxStreamingView,AbstractPdfStampView,AbstractFeedView,AbstractAtomFeedView, andAbstractRssFeedViewthat need to be replaced with direct usage of the underlying libraries (Apache POI, OpenPDF/iText, ROME) in web handlers.
- io.moderne.java.spring.framework7.FindThemeSupportUsage
- Find Spring Theme support usage
- Spring Framework 7.0 removes Theme support entirely. This recipe identifies usages of Theme-related classes like
ThemeResolver,ThemeSource, andThemeChangeInterceptorthat need to be removed or replaced with CSS-based alternatives. The Spring team recommends using CSS directly for theming functionality.
- io.moderne.java.spring.framework7.MigrateDeprecatedAPIs
- Migrate deprecated APIs removed in Spring Framework 7.0
- Migrates deprecated APIs that were removed in Spring Framework 7.0. This includes ListenableFuture to CompletableFuture migration, ContentCachingRequestWrapper constructor changes, and NestedServletException to ServletException type migration.
- io.moderne.java.spring.framework7.MigrateHttpStatusToRfc9110
- Migrate
HttpStatusenum values to RFC 9110 names - Spring Framework 7.0 aligns HttpStatus enum values with RFC 9110. This recipe replaces deprecated status code constants with their RFC 9110 equivalents:
PAYLOAD_TOO_LARGEbecomesCONTENT_TOO_LARGEandUNPROCESSABLE_ENTITYbecomesUNPROCESSABLE_CONTENT.
- Migrate
- io.moderne.java.spring.framework7.MigrateJackson2ObjectMapperBuilder
- Migrate
Jackson2ObjectMapperBuilderto mapper builder pattern - Replaces
Jackson2ObjectMapperBuilder.json().build()and similar factory methods with the corresponding Jackson mapper builder pattern (e.g.JsonMapper.builder()...build()). Setter calls on the resulting mapper are folded into the builder chain when safe, or annotated with a TODO comment when automatic migration is not possible.
- Migrate
- io.moderne.java.spring.framework7.MigrateJmsDestinationResolver
- Preserve DynamicDestinationResolver behavior for JmsTemplate
- Spring Framework 7.0 changed the default
DestinationResolverforJmsTemplatefromDynamicDestinationResolvertoSimpleDestinationResolver, which caches Session-resolved Queue and Topic instances. This recipe explicitly configuresDynamicDestinationResolverto preserve the pre-7.0 behavior. The caching behavior ofSimpleDestinationResolvershould be fine for most JMS brokers, so this explicit configuration can be removed once verified.
- io.moderne.java.spring.framework7.MigrateListenableFuture
- Migrate
ListenableFuturetoCompletableFuture - Spring Framework 6.0 deprecated
ListenableFuturein favor ofCompletableFuture. Spring Framework 7.0 removesListenableFutureentirely. This recipe migrates usages ofListenableFutureand its callbacks to useCompletableFutureandBiConsumerinstead.
- Migrate
- io.moderne.java.spring.framework7.MigrateResponseEntityGetStatusCodeValueMethod
- Migrate
ResponseEntity#getStatusCodeValue()togetStatusCode().value() - Replaces calls to
ResponseEntity#getStatusCodeValue()which was deprecated in Spring Framework 6.0 and removed in Spring Framework 7.0 withgetStatusCode().value().
- Migrate
- io.moderne.java.spring.framework7.RemoveSpringJcl
- Remove spring-jcl dependency
- The
spring-jclmodule has been removed in Spring Framework 7.0 in favor of Apache Commons Logging 1.3.0. This recipe removes any explicit dependency onorg.springframework:spring-jcl. The change should be transparent for most applications, as spring-jcl was typically a transitive dependency and the logging API calls (org.apache.commons.logging.*) remain unchanged.
- io.moderne.java.spring.framework7.RenameMemberCategoryConstants
- Rename MemberCategory field constants for Spring Framework 7.0
- Renames deprecated
MemberCategoryconstants to their new names in Spring Framework 7.0.MemberCategory.PUBLIC_FIELDSis renamed toMemberCategory.INVOKE_PUBLIC_FIELDSandMemberCategory.DECLARED_FIELDSis renamed toMemberCategory.INVOKE_DECLARED_FIELDS. These renames clarify the original intent of these categories and align with the rest of the API.
- io.moderne.java.spring.framework7.RenameRequestContextJstlPresent
- Rename
RequestContext.jstPresenttoJSTL_PRESENT - Renames the protected static field
RequestContext.jstPresenttoJSTL_PRESENTin Spring Framework 7.0. This field was renamed as part of a codebase-wide effort to use uppercase for classpath-related static final field names (see https://github.com/spring-projects/spring-framework/issues/35525).
- Rename
- io.moderne.java.spring.framework7.ReplaceJUnit4SpringTestBaseClasses
- Replace JUnit 4 Spring test base classes with JUnit Jupiter annotations
- Replace
AbstractJUnit4SpringContextTestsandAbstractTransactionalJUnit4SpringContextTestsbase classes with@ExtendWith(SpringExtension.class)and@Transactionalannotations. These base classes are deprecated in Spring Framework 7.0 in favor of the SpringExtension for JUnit Jupiter.
- io.moderne.java.spring.framework7.SimplifyReflectionHintRegistration
- Simplify reflection hint registrations for Spring Framework 7.0
- Removes deprecated
MemberCategoryarguments fromregisterType()calls onReflectionHints. In Spring Framework 7.0, registering a reflection hint for a type now implies methods, constructors, and fields introspection. AllMemberCategoryvalues exceptINVOKE_*have been deprecated. This recipe removes those deprecated arguments, simplifying code likehints.reflection().registerType(MyType.class, MemberCategory.DECLARED_FIELDS)tohints.reflection().registerType(MyType.class).
- io.moderne.java.spring.framework7.UpdateGraalVmNativeHints
- Update GraalVM native reflection hints for Spring Framework 7.0
- Migrates GraalVM native reflection hints to Spring Framework 7.0 conventions. Spring Framework 7.0 adopts the unified reachability metadata format for GraalVM. This recipe renames deprecated
MemberCategoryconstants and simplifies reflection hint registrations where explicit member categories are no longer needed.
- io.moderne.java.spring.framework7.UpgradeSpringFramework_7_0
- Migrate to Spring Framework 7.0
- Migrates applications to Spring Framework 7.0. This recipe applies all necessary changes including API migrations, removed feature detection, and configuration updates.
- io.moderne.java.spring.framework7.WrapGenericMessageMapInMessageHeaders
- Wrap
GenericMessagemap argument inMessageHeaders - Wraps the
Mapargument inGenericMessageconstructors in Kotlin sources withMessageHeaders(map)to explicitly use theMessageHeadersoverload. This resolves Kotlin overload resolution ambiguity between theMapandMessageHeadersconstructor overloads.
- Wrap
- io.moderne.java.spring.hibernate.MigrateDaoSupportGetSession
- Migrate
HibernateDaoSupport#getSession()usage - Migrate
HibernateDaoSupport#getSession()usage toHibernateDaoSupport#getSessionFactory()#getCurrentSession()and annotate the methods with@Transactional.
- Migrate
- io.moderne.java.spring.hibernate.MigrateSaveOrUpdateAll
- Migrate
HibernateDaoSupport#getHibernateTemplate#saveOrUpdateAll - Migrate removed
HibernateDaoSupport#getHibernateTemplate#.saveOrUpdateAllto an iterativeHibernateDaoSupport#getHibernateTemplate#.saveOrUpdate.
- Migrate
- io.moderne.java.spring.kafka.consumer.FindKafkaListenerWithoutErrorHandling
- Find
@KafkaListenermethods without error handling - Flags
@KafkaListenermethods that lack proper error handling. Methods should have@RetryableTopic, specify anerrorHandlerin the annotation, or implement try-catch blocks for error handling.
- Find
- io.moderne.java.spring.kafka.consumer.FindMissingDltHandler
- Find
@RetryableTopicwithout@DltHandler - Flags classes that use
@RetryableTopicwithout a corresponding@DltHandlermethod. A DLT handler should be defined to process messages that have exhausted all retries.
- Find
- io.moderne.java.spring.kafka.consumer.IsKafkaConsumer
- Is likely a Kafka consumer module
- Marks the project if it's likely a Kafka consumer module.
- io.moderne.java.spring.kafka.producer.FindCustomKeyUsage
- Find
KafkaTemplate.send()with custom key - Flags
KafkaTemplate.send()calls that use a custom key (3+ arguments). Custom keys should be reviewed to ensure they provide appropriate partition distribution.
- Find
- io.moderne.java.spring.kafka.producer.IsKafkaProducer
- Is likely a Kafka producer module
- Marks the project if it's likely a Kafka producer module.
- io.moderne.java.spring.orm.SpringORM5
- Migrate to Spring ORM to 5
- Migrate applications using Spring ORM Hibernate Support to Hibernate 5 compatible version. This will enable a further migration by the Spring Framework migration past 5.
- io.moderne.java.spring.security.MigrateAcegiToSpringSecurity_5_0
- Migrate from Acegi Security 1.0.x to Spring Security 5.0
- Migrates Acegi Security 1.0.x directly to Spring Security 5.0. This recipe handles dependency changes, type renames, XML configuration updates, web.xml filter migration, and adds TODO comments for password encoders that require manual migration.
- io.moderne.java.spring.security6.MigrateAntPathRequestMatcher
- Migrate antPathRequestMatcher to pathPatternRequestMatcher
- In Spring Security 6.5,
AntPathRequestMatcheris deprecated in favor ofPathPatternRequestMatcher. This recipe migrates static method calls and constructor usage to the new pattern.
- io.moderne.java.spring.security6.UpgradeSpringSecurity_6_5
- Migrate to Spring Security 6.5 (Moderne Edition)
- Migrate applications to the latest Spring Security 6.5 release. This recipe will modify an application's build files, make changes to deprecated/preferred APIs, and migrate configuration settings that have changes between versions.
- io.moderne.java.spring.security7.MigrateMvcRequestMatcher
- Migrate
MvcRequestMatchertoPathPatternRequestMatcher - In Spring Security 7.0,
MvcRequestMatcherwhich depends on the deprecatedHandlerMappingIntrospectoris removed in favor ofPathPatternRequestMatcher. This recipe migrates constructor and builder usage to the new pattern.
- Migrate
- io.moderne.java.spring.security7.MigrateOAuth2AccessTokenResponseClient
- Migrate
OAuth2AccessTokenResponseClientfromRestOperationstoRestClientbased implementations - A new set of
OAuth2AccessTokenResponseClientimplementations were introduced based onRestClient. This recipe replaces theRestOperations-based implementations which have been deprecated. TheRestClientimplementations are drop-in replacements for the deprecated implementations.
- Migrate
- io.moderne.java.spring.security7.MigrateOAuth2RestOperationsToRestClient
- Migrate OAuth2 token response client from
RestOperationstoRestClient - Migrates
setRestOperations(RestOperations)calls tosetRestClient(RestClient)on the newRestClient-based OAuth2AccessTokenResponseClientimplementations. TheRestClient-based implementations introduced in Spring Security 7 useRestClientinstead ofRestOperations.
- Migrate OAuth2 token response client from
- io.moderne.java.spring.security7.MigrateRequiresChannelToRedirectToHttps
- Migrate
requiresChannel()toredirectToHttps() - In Spring Security 7.0,
HttpSecurity.requiresChannel()is deprecated in favor ofHttpSecurity.redirectToHttps(). This recipe renames the method call and simplifiesanyRequest().requiresSecure()toCustomizer.withDefaults().
- Migrate
- io.moderne.java.spring.security7.ModularizeSpringSecurity7
- Spring Security 7 modularization
- Spring Security Core was modularized in version 7, deprecated classes that are still a crucial part of some applications are moved to
spring-security-access.
rewrite-tapestry
- org.openrewrite.tapestry.ChangeTapestryPackages
- Change Tapestry 4 packages to Tapestry 5
- Updates package imports from org.apache.tapestry to org.apache.tapestry5. Only renames packages that have direct equivalents in Tapestry 5.
- org.openrewrite.tapestry.ChangeTapestryTypes
- Change Tapestry 4 types to Tapestry 5 equivalents
- Renames Tapestry 4 types that have direct equivalents in Tapestry 5. This handles types from different packages that were reorganized in T5.
- org.openrewrite.tapestry.ConvertAnnotatedMethodToField
- Convert annotated abstract method to field
- Converts abstract getter methods annotated with
sourceAnnotationto private fields annotated withtargetAnnotation. Also removes corresponding abstract setter methods.
- org.openrewrite.tapestry.ConvertBeanAnnotation
- Convert Tapestry 4
@Beanto@Property - Converts Tapestry 4's
@Beanannotation to@Propertyfields. Bean initialization with 'initializer' attribute requires manual migration.
- Convert Tapestry 4
- org.openrewrite.tapestry.ConvertListenerInterfaces
- Convert Tapestry 4 listener interfaces to Tapestry 5 annotations
- Converts Tapestry 4 page lifecycle listener interfaces (
PageBeginRenderListener,PageEndRenderListener, etc.) to Tapestry 5 lifecycle annotations (@SetupRender,@CleanupRender, etc.) and removes the interface implementations.
- org.openrewrite.tapestry.MigrateTapestry4To5
- Migrate Tapestry 4 to Tapestry 5
- Migrates Apache Tapestry 4 applications to Tapestry 5. This includes package renames, removing base class inheritance, converting listener interfaces to annotations, and updating dependencies.
- org.openrewrite.tapestry.RemoveIRequestCycleParameter
- Remove
IRequestCycleparameters - Removes
IRequestCycleparameters from methods. In Tapestry 5, event handler methods don't receive the request cycle as a parameter.
- Remove
- org.openrewrite.tapestry.RemoveObsoleteFormTypes
- Remove obsolete Tapestry form types
- Removes field declarations and imports for Tapestry 4 form component types (
IPropertySelectionModel,StringPropertySelectionModel, etc.) that don't exist in Tapestry 5. Code using these types will need manual refactoring to use Tapestry 5'sSelectModelpattern.
- org.openrewrite.tapestry.RemoveTapestryBaseClasses
- Remove Tapestry 4 base classes
- Removes Tapestry 4 base class inheritance (
BasePage,BaseComponent,AbstractComponent) and converts the class to a POJO suitable for Tapestry 5. Abstract getter/setter methods are converted to fields with@Propertyannotation.
- org.openrewrite.tapestry.ReplaceReverseComparator
- Replace
ReverseComparatorwithCollections.reverseOrder() - Replaces tapestry-contrib's
ReverseComparatorwith the standard JavaCollections.reverseOrder()method.
- Replace
- org.openrewrite.tapestry.UpdateTapestryDependencies
- Update Tapestry dependencies
- Updates dependencies from Tapestry 4 to Tapestry 5.
rewrite-vulncheck
- io.moderne.vulncheck.FixVulnCheckVulnerabilities
- Use VulnCheck Exploit Intelligence to fix vulnerabilities
- This software composition analysis (SCA) tool detects and upgrades dependencies with publicly disclosed vulnerabilities. This recipe both generates a report of vulnerable dependencies and upgrades to newer versions with fixes. This recipe by default only upgrades to the latest patch version. If a minor or major upgrade is required to reach the fixed version, this can be controlled using the
maximumUpgradeDeltaoption. Vulnerability information comes from VulnCheck Vulnerability Intelligence. The recipe has an option to limit fixes to only those vulnerabilities that have evidence of exploitation at various levels of severity.
org.openrewrite
rewrite-python
- org.openrewrite.python.AddDependency
- Add Python dependency
- Add a dependency to a Python project. Supports
pyproject.toml(with scope/group targeting),requirements.txt, andPipfile. Whenuvis available, theuv.lockfile is regenerated.
- org.openrewrite.python.AddLiteralMethodArgument
- Add literal method argument
- Add a literal argument to method invocations matching a pattern.
- org.openrewrite.python.ChangeDependency
- Change Python dependency
- Change a dependency to a different package. Supports
pyproject.toml,requirements.txt, andPipfile. Searches all dependency scopes. Whenuvis available, theuv.lockfile is regenerated.
- org.openrewrite.python.ChangeImport
- Change import
- Change a Python import from one module/name to another, updating all type attributions.
- org.openrewrite.python.ChangeMethodName
- Change method name
- Rename method invocations matching a pattern.
- org.openrewrite.python.ChangePackage
- Change package
- Change package/module references from one name to another.
- org.openrewrite.python.ChangeType
- Change type
- Change a type reference from one fully qualified name to another.
- org.openrewrite.python.DeleteMethodArgument
- Delete method argument
- Remove an argument from method invocations matching a pattern.
- org.openrewrite.python.RemoveDependency
- Remove Python dependency
- Remove a dependency from a Python project. Supports
pyproject.toml(with scope/group targeting),requirements.txt, andPipfile. Whenuvis available, theuv.lockfile is regenerated.
- org.openrewrite.python.RemovePass
- Remove redundant pass statements
- Remove redundant
passstatements from Python code when there are other executable statements in the block.
- org.openrewrite.python.ReorderMethodArguments
- Reorder method arguments
- Reorder arguments in method invocations matching a pattern.
- org.openrewrite.python.UpgradeDependencyVersion
- Upgrade Python dependency version
- Upgrade the version constraint for a dependency. Supports
pyproject.toml(with scope/group targeting),requirements.txt, andPipfile. Whenuvis available, theuv.lockfile is regenerated.
- org.openrewrite.python.UpgradeTransitiveDependencyVersion
- Upgrade transitive Python dependency version
- Pin a transitive dependency version using the strategy appropriate for the file type and package manager. For
pyproject.toml: uv uses[tool.uv].constraint-dependencies, PDM uses[tool.pdm.overrides], and other managers add a direct dependency. Forrequirements.txtandPipfile: appends the dependency.
- org.openrewrite.python.format.PythonSpaces
- Formats spaces in Python code
- Standardizes spaces in Python code. Currently limited to formatting method arguments.
- org.openrewrite.python.search.DependencyInsight
- Python dependency insight
- Find direct and transitive Python dependencies matching a package name pattern. Results include dependencies that either directly match or transitively include a matching dependency.
org.openrewrite.recipe
rewrite-ai-search
- io.moderne.ai.FindCommentsLanguage
- Find comments' language distribution
- Finds all comments and uses AI to predict which language the comment is in.
- io.moderne.ai.FixMisencodedCommentsInFrench
- Fix mis-encoded French comments, javadocs and pom.xml comments
- Fixes mis-encoded French comments in your code, javadocs and in your pom.xml files. Mis-encoded comments contain a ? or � character.
- io.moderne.ai.ListAllMethodsUsed
- List all methods used
- List all methods used in any Java source file.
- io.moderne.ai.SpellCheckCommentsInFrench
- Fix mis-encoded comments in French
- Use spellchecker to fix mis-encoded French comments in comments, JavaDocs, properties or XML files. Mis-encoded comments will contain either '?' or '�'.
- io.moderne.ai.research.FindCodeThatResembles
- Find method invocations that resemble a pattern
- This recipe uses two phase AI approach to find a method invocation that resembles a search string.
- io.moderne.ai.research.GetCodeEmbedding
- Get embeddings for code snippets in code
- This recipe calls an AI model to get an embedding for either classes or methods which can then be used for downstream tasks.
- io.moderne.ai.research.GetRecommendations
- Get recommendations
- This recipe calls an AI model to get recommendations for modernizing the code base by looking at a sample of method declarations.
rewrite-android
- org.openrewrite.android.ChangeAndroidSdkVersion
- Change Android SDK version
- Change
compileSdk,compileSdkVersion,targetSdkandtargetSdkVersionin an Android Gradle build file to the argument version.
- org.openrewrite.android.MigrateToAndroidGradlePlugin_7_2
- Migrate to Android Gradle Plugin 7.2
- Recipes to migrate to Android Gradle Plugin version 7.2.
- org.openrewrite.android.MigrateToAndroidGradlePlugin_7_3
- Migrate to Android Gradle Plugin 7.3
- Recipes to migrate to Android Gradle Plugin version 7.3.
- org.openrewrite.android.MigrateToAndroidGradlePlugin_7_4
- Migrate to Android Gradle Plugin 7.4
- Recipes to migrate to Android Gradle Plugin version 7.4.
- org.openrewrite.android.MigrateToAndroidGradlePlugin_8_0
- Migrate to Android Gradle Plugin 8.0
- Recipes to migrate to Android Gradle Plugin version 8.0.
- org.openrewrite.android.MigrateToAndroidGradlePlugin_8_1
- Migrate to Android Gradle Plugin 8.1
- Recipes to migrate to Android Gradle Plugin version 8.1.
- org.openrewrite.android.MigrateToAndroidGradlePlugin_8_2
- Migrate to Android Gradle Plugin 8.2
- Recipes to migrate to Android Gradle Plugin version 8.2.
- org.openrewrite.android.MigrateToAndroidGradlePlugin_8_3
- Migrate to Android Gradle Plugin 8.3
- Recipes to migrate to Android Gradle Plugin version 8.3.
- org.openrewrite.android.MigrateToAndroidGradlePlugin_8_4
- Migrate to Android Gradle Plugin 8.4
- Recipes to migrate to Android Gradle Plugin version 8.4.
- org.openrewrite.android.MigrateToAndroidGradlePlugin_8_5
- Migrate to Android Gradle Plugin 8.5
- Recipes to migrate to Android Gradle Plugin version 8.5.
- org.openrewrite.android.MigrateToAndroidGradlePlugin_8_6
- Migrate to Android Gradle Plugin 8.6
- Recipes to migrate to Android Gradle Plugin version 8.6.
- org.openrewrite.android.MigrateToAndroidGradlePlugin_8_7
- Migrate to Android Gradle Plugin 8.7
- Recipes to migrate to Android Gradle Plugin version 8.7.
- org.openrewrite.android.UpgradeAndroidGradlePluginVersion
- Upgrade Android Gradle Plugin (AGP) version
- Upgrade Android Gradle Plugin (AGP) version and update the Gradle Wrapper version. Compatible versions are published in the AGP release notes.
- org.openrewrite.android.UpgradeToAndroidSDK33
- Upgrade to Android SDK 33
- Recipes to upgrade to Android SDK version 33.
- org.openrewrite.android.UpgradeToAndroidSDK34
- Upgrade to Android SDK 34
- Recipes to upgrade to Android SDK version 34.
- org.openrewrite.android.UpgradeToAndroidSDK35
- Upgrade to Android SDK 35
- Recipes to upgrade to Android SDK version 35.
rewrite-circleci
- org.openrewrite.circleci.InstallOrb
- Install an orb
- Install a CircleCI orb if it is not already installed.
- org.openrewrite.circleci.UpdateImage
- Update CircleCI image
- See the list of pre-built CircleCI images.
rewrite-codemods-ng
- org.openrewrite.codemods.migrate.angular.ApplyAngularCLI
- Upgrade Angular versions
- Run
ng updateto upgrade Angular CLI and Angular Core to the specified version.
- org.openrewrite.codemods.migrate.angular.v15
- Update to Angular v15
- Upgrade to Angular v15 through
ApplyAngularCLI.
- org.openrewrite.codemods.migrate.angular.v16
- Update to Angular v16
- Upgrade to Angular v16 through
ApplyAngularCLI.
- org.openrewrite.codemods.migrate.angular.v17
- Update to Angular v17
- Upgrade to Angular v17 through
ApplyAngularCLI.
- org.openrewrite.codemods.migrate.angular.v18
- Update to Angular v18
- Upgrade to Angular v18 through
ApplyAngularCLI.
- org.openrewrite.codemods.migrate.angular.v19
- Update to Angular v19
- Upgrade to Angular v19 through
ApplyAngularCLI.
- org.openrewrite.codemods.migrate.angular.v20
- Update to Angular v20
- Upgrade to Angular v20 through
ApplyAngularCLI.
- org.openrewrite.codemods.migrate.angular.v21
- Update to Angular v21
- Upgrade to Angular v21 through
ApplyAngularCLI.
rewrite-compiled-analysis
- io.moderne.compiled.verification.ChangeListMethodAndVerify
- Change
List#addtoList#plusand verify - We know this won't compile.
- Change
- io.moderne.compiled.verification.VerifyCompilation
- Verify compilation
- This is a task that runs after another recipe to verify that the changes made by that recipe would result in a successful compilation.
rewrite-concourse
- org.openrewrite.concourse.ChangeResourceVersion
- Change resource version
- Pin or unpin a resource to a particular version.
- org.openrewrite.concourse.ChangeValue
- Change Concourse value
- Change every value matching the key pattern.
- org.openrewrite.concourse.FindResource
- Find resource
- Find a Concourse resource by name.
- org.openrewrite.concourse.UpdateGitResourceUri
- Update git resource
source.urireferences - Update git resource
source.uriURI values to point to a new URI value.
- Update git resource
- org.openrewrite.concourse.search.FindPinnedResource
- Find pinned resources by type
- Find resources of a particular type that have pinned versions.
- org.openrewrite.concourse.search.FindPrivilegedResourceType
- Find privileged
resource_typedefinitions - By default,
resource_typedefinitions are unprivileged.
- Find privileged
rewrite-dotnet
- org.openrewrite.dotnet.MigrateToNet6
- Upgrade to .NET 6.0 using upgrade-assistant
- Run upgrade-assistant upgrade across a repository to upgrade projects to .NET 6.0.
- org.openrewrite.dotnet.MigrateToNet7
- Upgrade to .NET 7.0 using upgrade-assistant
- Run upgrade-assistant upgrade across a repository to upgrade projects to .NET 7.0.
- org.openrewrite.dotnet.MigrateToNet8
- Upgrade to .NET 8.0 using upgrade-assistant
- Run upgrade-assistant upgrade across a repository to upgrade projects to .NET 8.0.
- org.openrewrite.dotnet.MigrateToNet9
- Upgrade to .NET 9.0 using upgrade-assistant
- Run upgrade-assistant upgrade across a repository to upgrade projects to .NET 9.0.
- org.openrewrite.dotnet.UpgradeAssistant
- Upgrade a .NET project using upgrade-assistant
- Run upgrade-assistant upgrade across a repository to upgrade projects to a newer version of .NET.
- org.openrewrite.dotnet.UpgradeAssistantAnalyze
- Analyze a .NET project using upgrade-assistant
- Run upgrade-assistant analyze across a repository to analyze changes required to upgrade projects to a newer version of .NET. This recipe will generate an
org.openrewrite.dotnet.UpgradeAssistantAnalysisdata table containing the report details.
rewrite-java-security
- org.openrewrite.csharp.dependencies.DependencyInsight
- Dependency insight for C#
- Finds dependencies in
*.csprojandpackages.config.
- org.openrewrite.csharp.dependencies.DependencyVulnerabilityCheck
- Find and fix vulnerable Nuget dependencies
- This software composition analysis (SCA) tool detects and upgrades dependencies with publicly disclosed vulnerabilities. This recipe both generates a report of vulnerable dependencies and upgrades to newer versions with fixes. This recipe only upgrades to the latest patch version. If a minor or major upgrade is required to reach the fixed version, this recipe will not make any changes. Vulnerability information comes from the GitHub Security Advisory Database, which aggregates vulnerability data from several public databases, including the National Vulnerability Database maintained by the United States government. Dependencies following Semantic Versioning will see their patch version updated where applicable.
- org.openrewrite.csharp.dependencies.UpgradeDependencyVersion
- Upgrade C# dependency versions
- Upgrades dependencies in
*.csproj,Directory.Packages.props, andpackages.config.
- org.openrewrite.java.dependencies.AddExplicitTransitiveDependencies
- Add explicit transitive dependencies
- Detects when Java source code or configuration files reference types from transitive Maven dependencies and promotes those transitive dependencies to explicit direct dependencies in the pom.xml. This ensures the build is resilient against changes in transitive dependency trees of upstream libraries.
- org.openrewrite.java.dependencies.DependencyLicenseCheck
- Find licenses in use in third-party dependencies
- Locates and reports on all licenses in use.
- org.openrewrite.java.dependencies.DependencyVulnerabilityCheck
- Find and fix vulnerable dependencies
- This software composition analysis (SCA) tool detects and upgrades dependencies with publicly disclosed vulnerabilities. This recipe both generates a report of vulnerable dependencies and upgrades to newer versions with fixes. This recipe by default only upgrades to the latest patch version. If a minor or major upgrade is required to reach the fixed version, this can be controlled using the
maximumUpgradeDeltaoption. Vulnerability information comes from the GitHub Security Advisory Database, which aggregates vulnerability data from several public databases, including the National Vulnerability Database maintained by the United States government. Upgrades dependencies versioned according to Semantic Versioning. ## Customizing Vulnerability Data This recipe can be customized by extendingDependencyVulnerabilityCheckBaseand overriding the vulnerability data sources: -baselineVulnerabilities(ExecutionContext ctx): Provides the default set of known vulnerabilities. The base implementation loads vulnerability data from the GitHub Security Advisory Database CSV file usingResourceUtils.parseResourceAsCsv(). Override this method to replace the entire vulnerability dataset with your own curated list. -supplementalVulnerabilities(ExecutionContext ctx): Allows adding custom vulnerability data beyond the baseline. The base implementation returns an empty list. Override this method to add organization-specific vulnerabilities, internal security advisories, or vulnerabilities from additional sources while retaining the baseline GitHub Advisory Database. Both methods returnList<Vulnerability>objects. Vulnerability data can be loaded from CSV files usingResourceUtils.parseResourceAsCsv(path, Vulnerability.class, consumer)or constructed programmatically. To customize, extendDependencyVulnerabilityCheckBaseand override one or both methods depending on your needs. For example, overridesupplementalVulnerabilities()to add custom CVEs while keeping the standard vulnerability database, or overridebaselineVulnerabilities()to use an entirely different vulnerability data source. Last updated: 2026-04-20T1128.
- org.openrewrite.java.dependencies.RemoveUnusedDependencies
- Remove unused dependencies
- Scans through source code collecting references to types and methods, removing any dependencies that are not used from Maven or Gradle build files. This is best effort and not guaranteed to work well in all cases; false positives are still possible. This recipe takes reflective access into account: - When reflective access to a class is made unambiguously via a string literal, such as:
Class.forName("java.util.List")that is counted correctly. - When reflective access to a class is made ambiguously via anything other than a string literal no dependencies will be removed. This recipe takes transitive dependencies into account: - When a direct dependency is not used but a transitive dependency it brings in is in use the direct dependency is not removed.
- org.openrewrite.java.dependencies.SoftwareBillOfMaterials
- Software bill of materials
- Produces a software bill of materials (SBOM) for a project. An SBOM is a complete list of all dependencies used in a project, including transitive dependencies. The produced SBOM is in the CycloneDX XML format. Supports Gradle and Maven. Places a file named sbom.xml adjacent to the Gradle or Maven build file.
- org.openrewrite.java.security.FindTextDirectionChanges
- Find text-direction changes
- Finds unicode control characters which can change the direction text is displayed in. These control characters can alter how source code is presented to a human reader without affecting its interpretation by tools like compilers. So a malicious patch could pass code review while introducing vulnerabilities. Note that text direction-changing unicode control characters aren't inherently malicious. These characters can appear for legitimate reasons in code written in or dealing with right-to-left languages. See: https://trojansource.codes/ for more information.
- org.openrewrite.java.security.FixCwe338
- Fix CWE-338 with
SecureRandom - Use a cryptographically strong pseudo-random number generator (PRNG).
- Fix CWE-338 with
- org.openrewrite.java.security.FixCwe918
- Remediate server-side request forgery (SSRF)
- Inserts a guard that validates URLs constructed from user-controlled input do not target internal network addresses, blocking server-side request forgery (SSRF) attacks.
- org.openrewrite.java.security.ImproperPrivilegeManagement
- Improper privilege management
- Marking code as privileged enables a piece of trusted code to temporarily enable access to more resources than are available directly to the code that called it.
- org.openrewrite.java.security.JavaSecurityBestPractices
- Java security best practices
- Applies security best practices to Java code.
- org.openrewrite.java.security.Owasp2025A01
- Remediate OWASP A01:2025 Broken access control
- OWASP A01:2025 describes failures related to broken access control.
- org.openrewrite.java.security.Owasp2025A02
- Remediate OWASP A02:2025 Security misconfiguration
- OWASP A02:2025 describes failures related to security misconfiguration. Previously A05:2021, this category moved up to #2 in 2025.
- org.openrewrite.java.security.Owasp2025A03
- Remediate OWASP A03:2025 Software supply chain failures
- OWASP A03:2025 describes failures related to the software supply chain, including vulnerable and outdated components. Expanded from A06:2021 Vulnerable and Outdated Components.
- org.openrewrite.java.security.Owasp2025A04
- Remediate OWASP A04:2025 Cryptographic failures
- OWASP A04:2025 describes failures related to cryptography (or lack thereof), which often lead to exposure of sensitive data. Previously A02:2021.
- org.openrewrite.java.security.Owasp2025A05
- Remediate OWASP A05:2025 Injection
- OWASP A05:2025 describes failures related to user-supplied data being used to influence program state to operate outside of its intended bounds. Previously A03:2021.
- org.openrewrite.java.security.OwaspA01
- Remediate OWASP A01:2021 Broken access control
- OWASP A01:2021 describes failures related to broken access control.
- org.openrewrite.java.security.OwaspA02
- Remediate OWASP A02:2021 Cryptographic failures
- OWASP A02:2021 describes failures related to cryptography (or lack thereof), which often lead to exposure of sensitive data. This recipe seeks to remediate these vulnerabilities.
- org.openrewrite.java.security.OwaspA03
- Remediate OWASP A03:2021 Injection
- OWASP A03:2021 describes failures related to user-supplied data being used to influence program state to operate outside of its intended bounds. This recipe seeks to remediate these vulnerabilities.
- org.openrewrite.java.security.OwaspA05
- Remediate OWASP A05:2021 Security misconfiguration
- OWASP A05:2021 describes failures related to security misconfiguration.
- org.openrewrite.java.security.OwaspA06
- Remediate OWASP A06:2021 Vulnerable and outdated components
- OWASP A06:2021 describes failures related to vulnerable and outdated components.
- org.openrewrite.java.security.OwaspA08
- Remediate OWASP A08:2021 Software and data integrity failures
- OWASP A08:2021 software and data integrity failures.
- org.openrewrite.java.security.OwaspTopTen
- Remediate vulnerabilities from the OWASP Top Ten
- OWASP publishes a list of the most impactful common security vulnerabilities. These recipes identify and remediate vulnerabilities from the OWASP Top Ten.
- org.openrewrite.java.security.PartialPathTraversalVulnerability
- Partial path traversal vulnerability
- Replaces
dir.getCanonicalPath().startsWith(parent.getCanonicalPath(), which is vulnerable to partial path traversal attacks, with the more securedir.getCanonicalFile().toPath().startsWith(parent.getCanonicalFile().toPath()). To demonstrate this vulnerability, consider"/usr/outnot".startsWith("/usr/out"). The check is bypassed although/outnotis not under the/outdirectory. It's important to understand that the terminating slash may be removed when using variousStringrepresentations of theFileobject. For example, on Linux,println(new File("/var"))will print/var, butprintln(new File("/var", "/")will print/var/; however,println(new File("/var", "/").getCanonicalPath())will print/var.
- org.openrewrite.java.security.RegularExpressionDenialOfService
- Regular Expression Denial of Service (ReDOS)
- ReDoS is a Denial of Service attack that exploits the fact that most Regular Expression implementations may reach extreme situations that cause them to work very slowly (exponentially related to input size). See the OWASP description of this attack here for more details.
- org.openrewrite.java.security.SecureRandom
- Secure random
- Use cryptographically secure Pseudo Random Number Generation in the "main" source set. Replaces instantiation of
java.util.Randomwithjava.security.SecureRandom.
- org.openrewrite.java.security.SecureRandomPrefersDefaultSeed
- SecureRandom seeds are not constant or predictable
- Remove
SecureRandom#setSeed(*)method invocations having constant or predictable arguments.
- org.openrewrite.java.security.SecureTempFileCreation
- Use secure temporary file creation
java.io.File.createTempFile()has exploitable default file permissions. This recipe migrates to the more securejava.nio.file.Files.createTempFile().
- org.openrewrite.java.security.UseFilesCreateTempDirectory
- Use
Files#createTempDirectory - Use
Files#createTempDirectorywhen the sequenceFile#createTempFile(..)->File#delete()->File#mkdir()is used for creating a temp directory.
- Use
- org.openrewrite.java.security.XmlParserXXEVulnerability
- XML parser XXE vulnerability
- Avoid exposing dangerous features of the XML parser by updating certain factory settings.
- org.openrewrite.java.security.ZipSlip
- Zip slip
- Zip slip is an arbitrary file overwrite critical vulnerability, which typically results in remote command execution. A fuller description of this vulnerability is available in the Snyk documentation on it.
- org.openrewrite.java.security.marshalling.InsecureJmsDeserialization
- Insecure JMS deserialization
- JMS
Objectmessages depend on Java Serialization for marshalling/unmarshalling of the message payload whenObjectMessage#getObjectis called. Deserialization of untrusted data can lead to security flaws.
- org.openrewrite.java.security.marshalling.SecureJacksonDefaultTyping
- Secure the use of Jackson default typing
- See the blog post on this subject.
- org.openrewrite.java.security.marshalling.SecureSnakeYamlConstructor
- Secure the use of SnakeYAML's constructor
- See the paper on this subject.
- org.openrewrite.java.security.search.FindCommandInjection
- Find OS command injection vectors
- Finds calls to
Runtime.exec(String)which passes the command through a shell interpreter, enabling command injection via metacharacters like;,|, and&&. Use theString[]overload instead to avoid shell interpretation.
- org.openrewrite.java.security.search.FindExpressionLanguageInjection
- Find Expression Language injection vectors
- Finds calls to Expression Language (EL) evaluation methods which, when the expression is built from user input, can allow arbitrary code execution. Use parameterized expressions or input validation instead.
- org.openrewrite.java.security.search.FindHardcodedIv
- Find hardcoded initialization vectors
- Finds
IvParameterSpecconstructed with hardcoded byte arrays or string literals. A static IV makes CBC and other modes deterministic, enabling chosen-plaintext attacks. IVs should be generated randomly usingSecureRandomfor each encryption operation.
- org.openrewrite.java.security.search.FindHttpResponseSplitting
- Find HTTP response splitting vectors
- Finds calls to
HttpServletResponse.addHeader(),setHeader(), andaddCookie()which, when header values are derived from user input without CRLF sanitization, can allow HTTP response splitting attacks. Full taint-based detection requires rewrite-program-analysis; this recipe identifies the sink call sites for manual review.
- org.openrewrite.java.security.search.FindInadequateKeySize
- Find inadequate cryptographic key sizes
- Finds cryptographic key generation with inadequate key sizes. RSA keys should be at least 2048 bits, DSA keys at least 2048 bits, EC keys at least 256 bits, and symmetric keys (AES) at least 128 bits. NIST recommends RSA-2048+ and AES-128+ as minimum for all new applications.
- org.openrewrite.java.security.search.FindJacksonDefaultTypeMapping
- Find Jackson default type mapping enablement
ObjectMapper#enableTypeMapping(..)can lead to vulnerable deserialization.
- org.openrewrite.java.security.search.FindPermissiveCorsConfiguration
- Find permissive CORS configuration
- Finds overly permissive CORS configurations that allow all origins, which can expose the application to cross-domain attacks.
- org.openrewrite.java.security.search.FindPredictableSalt
- Find predictable cryptographic salts
- Finds
PBEParameterSpecandPBEKeySpecconstructed with hardcoded salt byte arrays. A predictable salt undermines the purpose of salting, making rainbow table and precomputation attacks feasible. Salts should be generated randomly usingSecureRandom.
- org.openrewrite.java.security.search.FindProcessControl
- Find process control vectors
- Finds calls to
System.loadLibrary(),System.load(), andRuntime.load()which, when the library path or name is derived from user input, can allow an attacker to load arbitrary native code. Ensure library names are not externally controlled.
- org.openrewrite.java.security.search.FindResourceInjection
- Find resource injection vectors
- Detects resource injection vulnerabilities where user-controlled input flows to resource access operations — file paths, JNDI lookups, class loading, and native library loading. Uses taint analysis from rewrite-program-analysis for source-to-sink tracking with sanitizer support, plus structural detection as fallback.
- org.openrewrite.java.security.search.FindRsaWithoutOaep
- Find RSA encryption without OAEP padding
- Finds uses of RSA encryption with PKCS#1 v1.5 padding or no padding specification. RSA without OAEP padding is vulnerable to padding oracle attacks. Use
RSA/ECB/OAEPWithSHA-256AndMGF1Paddingor equivalent OAEP mode instead.
- org.openrewrite.java.security.search.FindScriptEngineInjection
- Find script engine code injection vectors
- Finds calls to
ScriptEngine.eval()which can execute arbitrary code if the script string is influenced by user input. Consider sandboxing or removing dynamic script evaluation.
- org.openrewrite.java.security.search.FindSensitiveApiEndpoints
- Find sensitive API endpoints
- Find data models exposed by REST APIs that contain sensitive information like PII and secrets.
- org.openrewrite.java.security.search.FindSqlInjection
- Find potential SQL injection
- Finds SQL query methods where the query string is constructed via string concatenation, which may indicate SQL injection vulnerabilities. Use parameterized queries or prepared statements instead.
- org.openrewrite.java.security.search.FindUnsafeReflection
- Find unsafe reflection vectors
- Finds calls to
Class.forName()which, when the class name is derived from user input, can allow an attacker to instantiate arbitrary classes. Review these call sites to ensure the class name is not externally controlled.
- org.openrewrite.java.security.search.FindVulnerableJacksonJsonTypeInfo
- Find vulnerable uses of Jackson
@JsonTypeInfo - Identify where attackers can deserialize gadgets into a target field.
- Find vulnerable uses of Jackson
- org.openrewrite.java.security.search.FindWeakCryptoAlgorithm
- Find weak cryptographic algorithms
- Finds uses of broken or risky cryptographic algorithms such as MD5, SHA-1, DES, DESede (3DES), RC2, RC4, and Blowfish in calls to
Cipher.getInstance(),MessageDigest.getInstance(),Mac.getInstance(),KeyGenerator.getInstance(), andSecretKeyFactory.getInstance().
- org.openrewrite.java.security.search.FindWeakPasswordHashing
- Find weak password hashing
- Finds uses of
MessageDigest.getInstance()with algorithms unsuitable for password hashing (MD5, SHA-1, SHA-256, SHA-384, SHA-512). Passwords should be hashed with a purpose-built password hashing function such as bcrypt, scrypt, Argon2, or PBKDF2 that includes a salt and a tunable work factor.
- org.openrewrite.java.security.search.FindXPathInjection
- Find XPath injection vectors
- Finds calls to
XPath.evaluate()andXPath.compile()which, when the expression is built from user input, can allow XPath injection attacks. Use parameterized XPath expressions or input validation instead.
- org.openrewrite.java.security.secrets.FindArtifactorySecrets
- Find Artifactory secrets
- Locates Artifactory secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindAwsSecrets
- Find AWS secrets
- Locates AWS secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindAzureSecrets
- Find Azure secrets
- Locates Azure secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindDiscordSecrets
- Find Discord secrets
- Locates Discord secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindFacebookSecrets
- Find Facebook secrets
- Locates Facebook secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindGenericSecrets
- Find generic secrets
- Locates generic secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindGitHubSecrets
- Find GitHub secrets
- Locates GitHub secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindGoogleSecrets
- Find Google secrets
- Locates Google secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindHerokuSecrets
- Find Heroku secrets
- Locates Heroku secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindJwtSecrets
- Find JWT secrets
- Locates JWTs stored in plain text in code.
- org.openrewrite.java.security.secrets.FindMailChimpSecrets
- Find MailChimp secrets
- Locates MailChimp secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindMailgunSecrets
- Find Mailgun secrets
- Locates Mailgun secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindNpmSecrets
- Find NPM secrets
- Locates NPM secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindPasswordInUrlSecrets
- Find passwords used in URLs
- Locates URLs that contain passwords in plain text.
- org.openrewrite.java.security.secrets.FindPayPalSecrets
- Find PayPal secrets
- Locates PayPal secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindPgpSecrets
- Find PGP secrets
- Locates PGP secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindPicaticSecrets
- Find Picatic secrets
- Locates Picatic secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindRsaSecrets
- Find RSA private keys
- Locates RSA private keys stored in plain text in code.
- org.openrewrite.java.security.secrets.FindSecrets
- Find secrets
- Locates secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindSecretsByPattern
- Find secrets with regular expressions
- A secret is a literal that matches any one of the provided patterns.
- org.openrewrite.java.security.secrets.FindSendGridSecrets
- Find SendGrid secrets
- Locates SendGrid secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindSlackSecrets
- Find Slack secrets
- Locates Slack secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindSquareSecrets
- Find Square secrets
- Locates Square secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindSshSecrets
- Find SSH secrets
- Locates SSH secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindStripeSecrets
- Find Stripe secrets
- Locates Stripe secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindTelegramSecrets
- Find Telegram secrets
- Locates Telegram secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindTwilioSecrets
- Find Twilio secrets
- Locates Twilio secrets stored in plain text in code.
- org.openrewrite.java.security.secrets.FindTwitterSecrets
- Find Twitter secrets
- Locates Twitter secrets stored in plain text in code.
- org.openrewrite.java.security.servlet.CookieSetHttpOnly
- Cookies missing HttpOnly flag
- Check for use of cookies without the HttpOnly flag. Cookies should be marked as HttpOnly to prevent client-side scripts from accessing them, reducing the risk of cross-site scripting (XSS) attacks.
- org.openrewrite.java.security.servlet.CookieSetSecure
- Insecure cookies
- Check for use of insecure cookies. Cookies should be marked as secure. This ensures that the cookie is sent only over HTTPS to prevent cross-site scripting attacks.
- org.openrewrite.java.security.spring.CsrfProtection
- Enable CSRF attack prevention
- Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious web site, email, blog, instant message, or program causes a user's web browser to perform an unwanted action on a trusted site when the user is authenticated. See the full OWASP cheatsheet.
- org.openrewrite.java.security.spring.InsecureSpringServiceExporter
- Secure Spring service exporters
- The default Java deserialization mechanism is available via
ObjectInputStreamclass. This mechanism is known to be vulnerable. If an attacker can make an application deserialize malicious data, it may result in arbitrary code execution. Spring’sRemoteInvocationSerializingExporteruses the default Java deserialization mechanism to parse data. As a result, all classes that extend it are vulnerable to deserialization attacks. The Spring Framework contains at leastHttpInvokerServiceExporterandSimpleHttpInvokerServiceExporterthat extendRemoteInvocationSerializingExporter. These exporters parse data from the HTTP body using the unsafe Java deserialization mechanism. See the full blog post by Artem Smotrakov on CVE-2016-1000027 from which the above description is excerpted.
- org.openrewrite.java.security.spring.PreventClickjacking
- Prevent clickjacking
- The
frame-ancestorsdirective can be used in a Content-Security-Policy HTTP response header to indicate whether or not a browser should be allowed to render a page in a<frame>or<iframe>. Sites can use this to avoid Clickjacking attacks by ensuring that their content is not embedded into other sites.
- org.openrewrite.java.security.spring.RemoveEnableWebSecurityDebug
- Remove debug mode from Spring Security
- Removes the debug attribute from @EnableWebSecurity annotations to prevent sensitive security information from being logged in production.
- org.openrewrite.python.dependencies.DependencyVulnerabilityCheck
- Find and fix vulnerable PyPI dependencies
- This software composition analysis (SCA) tool detects and upgrades dependencies with publicly disclosed vulnerabilities. This recipe both generates a report of vulnerable dependencies and upgrades to newer versions with fixes. This recipe by default only upgrades to the latest patch version. If a minor or major upgrade is required to reach the fixed version, this can be controlled using the
maximumUpgradeDeltaoption. Vulnerability information comes from the GitHub Security Advisory Database, which aggregates vulnerability data from several public databases, including the National Vulnerability Database maintained by the United States government. Dependencies following Semantic Versioning will see their patch version updated where applicable. ## Customizing Vulnerability Data This recipe can be customized by extendingDependencyVulnerabilityCheckBaseand overriding the vulnerability data sources: -baselineVulnerabilities(ExecutionContext ctx): Provides the default set of known vulnerabilities. The base implementation loads vulnerability data from the GitHub Security Advisory Database CSV file usingResourceUtils.parseResourceAsCsv(). Override this method to replace the entire vulnerability dataset with your own curated list. -supplementalVulnerabilities(ExecutionContext ctx): Allows adding custom vulnerability data beyond the baseline. The base implementation returns an empty list. Override this method to add organization-specific vulnerabilities, internal security advisories, or vulnerabilities from additional sources while retaining the baseline GitHub Advisory Database. Both methods returnList<Vulnerability>objects. Vulnerability data can be loaded from CSV files usingResourceUtils.parseResourceAsCsv(path, Vulnerability.class, consumer)or constructed programmatically. To customize, extendDependencyVulnerabilityCheckBaseand override one or both methods depending on your needs. For example, overridesupplementalVulnerabilities()to add custom CVEs while keeping the standard vulnerability database, or overridebaselineVulnerabilities()to use an entirely different vulnerability data source.
- org.openrewrite.recipe.rewrite-java-security.InlineDeprecatedMethods
- Inline deprecated delegating methods
- Automatically generated recipes to inline deprecated method calls that delegate to other methods in the same class.
- org.openrewrite.text.FindHardcodedLoopbackAddresses
- Find hard-coded loopback IPv4 addresses
- Locates mentions of hard-coded IPv4 addresses from the loopback IP range. The loopback IP range includes
127.0.0.0to127.255.255.255. This detects the entire localhost/loopback subnet range, not just the commonly used127.0.0.1.
- org.openrewrite.text.FindHardcodedPrivateIPAddresses
- Find hard-coded private IPv4 addresses
- Locates mentions of hard-coded IPv4 addresses from private IP ranges. Private IP ranges include: *
192.168.0.0to192.168.255.255*10.0.0.0to10.255.255.255*172.16.0.0to172.31.255.255It is not detecting the localhost subnet127.0.0.0to127.255.255.255.
- org.openrewrite.text.RemoveHardcodedIPAddressesFromComments
- Remove hard-coded IP addresses from comments
- Removes hard-coded IPv4 addresses from comments when they match private IP ranges or loopback addresses. This targets IP addresses that are commented out in various comment formats: Private IP ranges: *
192.168.0.0to192.168.255.255*10.0.0.0to10.255.255.255*172.16.0.0to172.31.255.255Loopback IP range: *127.0.0.0to127.255.255.255Supported comment formats: * C-style line comments (//) * C-style block comments (/* */) * Shell/Python style comments (#) * XML comments (<!-- -->) * YAML comments (#) * Properties file comments (#or!) For line comments, the entire line is removed. For block comments, only the IP address is removed.
rewrite-kubernetes
- org.openrewrite.kubernetes.AddConfiguration
- Add Kubernetes configuration
- Add default required configuration when it is missing.
- org.openrewrite.kubernetes.ChangeApiVersion
- Change Kubernetes API version
- Change the Kubernetes API version in a resource.
- org.openrewrite.kubernetes.ImagePullPolicyAlways
- Ensure image pull policy is
Always - Ensures the latest version of a tag is deployed each time.
- Ensure image pull policy is
- org.openrewrite.kubernetes.KubernetesBestPractices
- Kubernetes best practices
- Applies best practices to Kubernetes manifests.
- org.openrewrite.kubernetes.LifecycleRuleOnStorageBucket
- Ensure lifecycle rule on
StorageBucket - When defining a rule, you can specify any set of conditions for any action. The following configuration defines a rule to delete all objects older than 7 days in a bucket.
- Ensure lifecycle rule on
- org.openrewrite.kubernetes.LimitContainerCapabilities
- Limit root capabilities in a container
- Limiting the admission of containers with capabilities ensures that only a small number of containers have extended capabilities outside the default range.
- org.openrewrite.kubernetes.MissingCpuLimits
- Ensure CPU limits are set
- A system without managed quotas could eventually collapse due to inadequate resources for the tasks it bares.
- org.openrewrite.kubernetes.MissingCpuRequest
- Ensure CPU request is set
- If a container is created in a namespace that has a default CPU limit, and the container does not specify its own CPU limit, then the container is assigned the default CPU limit.
- org.openrewrite.kubernetes.MissingMemoryLimits
- Ensure memory limits are set
- With no limit set, kubectl allocates more and more memory to the container until it runs out.
- org.openrewrite.kubernetes.MissingMemoryRequest
- Ensure memory request is set
- A container is guaranteed to have as much memory as it requests, but is not allowed to use more memory than the limit set. This configuration may save resources and prevent an attack on an exploited container.
- org.openrewrite.kubernetes.MissingPodLivenessProbe
- Ensure liveness probe is configured
- The kubelet uses liveness probes to know when to schedule restarts for containers. Restarting a container in a deadlock state can help to make the application more available, despite bugs.
- org.openrewrite.kubernetes.MissingPodReadinessProbe
- Ensure readiness probe is configured
- Using the Readiness Probe ensures teams define what actions need to be taken to prevent failure and ensure recovery in case of unexpected errors.
- org.openrewrite.kubernetes.NoHostIPCSharing
- No host IPC sharing
- Preventing sharing of host PID/IPC namespace, networking, and ports ensures proper isolation between Docker containers and the underlying host.
- org.openrewrite.kubernetes.NoHostNetworkSharing
- No host network sharing
- When using the host network mode for a container, that container’s network stack is not isolated from the Docker host, so the container shares the host’s networking namespace and does not get its own IP-address allocation.
- org.openrewrite.kubernetes.NoHostProcessIdSharing
- No host process ID sharing
- Sharing the host process ID namespace breaks the isolation between container images and can make processes visible to other containers in the pod. This includes all information in the /proc directory, which can sometimes include passwords or keys, passed as environment variables.
- org.openrewrite.kubernetes.NoPrivilegeEscalation
- No privilege escalation
- Does not allow a process to gain more privileges than its parent process.
- org.openrewrite.kubernetes.NoPrivilegedContainers
- No privileged containers
- Privileged containers are containers that have all of the root capabilities of a host machine, allowing access to resources that are not accessible in ordinary containers.
- org.openrewrite.kubernetes.NoRootContainers
- No root containers
- Containers that run as root frequently have more permissions than their workload requires which, in case of compromise, could help an attacker further their exploits.
- org.openrewrite.kubernetes.ReadOnlyRootFilesystem
- Read-only root filesystem
- Using an immutable root filesystem and a verified boot mechanism prevents against attackers from "owning" the machine through permanent local changes.
- org.openrewrite.kubernetes.UpdateContainerImageName
- Update image name
- Search for image names that match patterns and replace the components of the name with new values.
- org.openrewrite.kubernetes.migrate.MigrateToAPIv1_16
- Migrate to Kubernetes API v1.16
- This recipe will apply changes commonly needed when migrating to Kubernetes API v1.16.
- org.openrewrite.kubernetes.migrate.MigrateToAPIv1_22
- Migrate to Kubernetes API v1.22
- This recipe will apply changes commonly needed when migrating to Kubernetes API v1.22.
- org.openrewrite.kubernetes.migrate.MigrateToAPIv1_25
- Migrate to Kubernetes API v1.25
- This recipe will apply changes commonly needed when migrating to Kubernetes API v1.25.
- org.openrewrite.kubernetes.migrate.MigrateToAPIv1_26
- Migrate to Kubernetes API v1.26
- This recipe will apply changes commonly needed when migrating to Kubernetes API v1.26.
- org.openrewrite.kubernetes.migrate.MigrateToAPIv1_27
- Migrate to Kubernetes API v1.27
- This recipe will apply changes commonly needed when migrating to Kubernetes API v1.27.
- org.openrewrite.kubernetes.migrate.MigrateToAPIv1_29
- Migrate to Kubernetes API v1.29
- This recipe will apply changes commonly needed when migrating to Kubernetes API v1.29.
- org.openrewrite.kubernetes.migrate.MigrateToAPIv1_32
- Migrate to Kubernetes API v1.32
- This recipe will apply changes commonly needed when migrating to Kubernetes API v1.32.
- org.openrewrite.kubernetes.migrate.MigrateToAPIv1_33
- Migrate to Kubernetes API v1.33
- This recipe will apply changes commonly needed when migrating to Kubernetes API v1.33.
- org.openrewrite.kubernetes.migrate.MigrateToAPIv1_34
- Migrate to Kubernetes API v1.34
- This recipe will apply changes commonly needed when migrating to Kubernetes API v1.34.
- org.openrewrite.kubernetes.migrate.MigrateToAPIv1_35
- Migrate to Kubernetes API v1.35
- This recipe will apply changes commonly needed when migrating to Kubernetes API v1.35.
- org.openrewrite.kubernetes.rbac.AddRuleToRole
- Add RBAC rules
- Add RBAC rules to ClusterRoles or namespaced Roles.
- org.openrewrite.kubernetes.resource.CapResourceValueToMaximum
- Cap exceeds resource value
- Cap resource values that exceed a specific maximum.
- org.openrewrite.kubernetes.resource.FindExceedsResourceRatio
- Find exceeds resource ratio
- Find resource manifests that have requests to limits ratios beyond a specific maximum.
- org.openrewrite.kubernetes.resource.FindExceedsResourceValue
- Find exceeds resource limit
- Find resource manifests that have limits set beyond a specific maximum.
- org.openrewrite.kubernetes.search.FindAnnotation
- Find annotation
- Find annotations that optionally match a given regex.
- org.openrewrite.kubernetes.search.FindDisallowedImageTags
- Find disallowed image tags
- The set of image tags to find which are considered disallowed.
- org.openrewrite.kubernetes.search.FindHarcodedIPAddresses
- Find hardcoded IP addresses
- Find hardcoded IP address anywhere in text-based files.
- org.openrewrite.kubernetes.search.FindImage
- Find image by name
- The image name to search for in containers and initContainers.
- org.openrewrite.kubernetes.search.FindMissingDigest
- Find missing image digest
- Find instances of a container name that fails to specify a digest.
- org.openrewrite.kubernetes.search.FindMissingOrInvalidAnnotation
- Find annotation
- Find annotations that optionally match a given value.
- org.openrewrite.kubernetes.search.FindMissingOrInvalidLabel
- Find label
- Find labels that optionally match a given regex.
- org.openrewrite.kubernetes.search.FindNonTlsIngress
- Find non-TLS Ingresses
- Find Ingress resources that don't disallow HTTP or don't have TLS configured.
- org.openrewrite.kubernetes.search.FindResourceMissingConfiguration
- Find missing configuration
- Find Kubernetes resources with missing configuration.
- org.openrewrite.kubernetes.services.FindServiceExternalIPs
- Find uses of
externalIP - Find any
ServicewhoseexternalIPlist contains, or does not contain, one of a list of IPs.
- Find uses of
- org.openrewrite.kubernetes.services.FindServicesByType
- Service type
- Type of Kubernetes
Serviceto find.
- org.openrewrite.kubernetes.services.UpdateServiceExternalIP
- Update
ServiceexternalIP - Swap out an IP address with another one in
ServiceexternalIPsettings.
- Update
rewrite-migrate-kotlin
- androidx.compose.animation.ReplaceDeprecatedAnimationCore1Methods
- Replace deprecated
animation-coremethods - Automatically generated recipes to replace deprecated Kotlin methods based on
@Deprecated(replaceWith=ReplaceWith(...))annotations.
- Replace deprecated
- androidx.compose.material.ReplaceDeprecatedMaterial1Methods
- Replace deprecated
materialmethods - Automatically generated recipes to replace deprecated Kotlin methods based on
@Deprecated(replaceWith=ReplaceWith(...))annotations.
- Replace deprecated
- androidx.compose.material3.ReplaceDeprecatedMaterial31Methods
- Replace deprecated
material3methods - Automatically generated recipes to replace deprecated Kotlin methods based on
@Deprecated(replaceWith=ReplaceWith(...))annotations.
- Replace deprecated
- androidx.compose.runtime.ReplaceDeprecatedRuntime1Methods
- Replace deprecated
runtimemethods - Automatically generated recipes to replace deprecated Kotlin methods based on
@Deprecated(replaceWith=ReplaceWith(...))annotations.
- Replace deprecated
- org.jetbrains.kotlinx.ReplaceDeprecatedKotlinxCollectionsImmutable0Methods
- Replace deprecated
kotlinx-collections-immutablemethods - Automatically generated recipes to replace deprecated Kotlin methods based on
@Deprecated(replaceWith=ReplaceWith(...))annotations.
- Replace deprecated
- org.jetbrains.kotlinx.ReplaceDeprecatedKotlinxCoroutinesCore1Methods
- Replace deprecated
kotlinx-coroutines-coremethods - Automatically generated recipes to replace deprecated Kotlin methods based on
@Deprecated(replaceWith=ReplaceWith(...))annotations.
- Replace deprecated
- org.jetbrains.kotlinx.ReplaceDeprecatedKotlinxDatetime0Methods
- Replace deprecated
kotlinx-datetimemethods - Automatically generated recipes to replace deprecated Kotlin methods based on
@Deprecated(replaceWith=ReplaceWith(...))annotations.
- Replace deprecated
- org.jetbrains.kotlinx.ReplaceDeprecatedKotlinxIoCore0Methods
- Replace deprecated
kotlinx-io-coremethods - Automatically generated recipes to replace deprecated Kotlin methods based on
@Deprecated(replaceWith=ReplaceWith(...))annotations.
- Replace deprecated
- org.jetbrains.kotlinx.ReplaceDeprecatedKotlinxSerializationCore1Methods
- Replace deprecated
kotlinx-serialization-coremethods - Automatically generated recipes to replace deprecated Kotlin methods based on
@Deprecated(replaceWith=ReplaceWith(...))annotations.
- Replace deprecated
- org.openrewrite.kotlin.compose.ReplaceDeprecatedComposeMethods
- Replace deprecated Jetpack Compose methods
- Replace deprecated Jetpack Compose method calls with their recommended replacements, based on
@Deprecated(replaceWith=ReplaceWith(...))annotations.
- org.openrewrite.kotlin.exposed.ExposedChangeMethodNames
- Rename Exposed deprecated methods for 1.0
- Rename deprecated Exposed method and property references to their 1.0 replacements.
- org.openrewrite.kotlin.exposed.ExposedChangeTypes
- Migrate Exposed type references to 1.0 packages
- Change fully qualified type references from Exposed 0.x packages to Exposed 1.0 packages. The 1.0 release reorganized all packages under
org.jetbrains.exposed.v1.*and split classes acrosscore,jdbc, anddaomodules.
- org.openrewrite.kotlin.exposed.ExposedUpgradeGradleDependencies
- Upgrade Exposed Gradle dependencies to 1.0
- Update JetBrains Exposed Gradle dependencies for the 1.0.0 migration. Upgrades dependency versions and handles the
exposed-migrationmodule split.
- org.openrewrite.kotlin.exposed.UpgradeToExposed_1
- Migrate to JetBrains Exposed 1.0
- Migrate from JetBrains Exposed 0.x to 1.0.0. This includes package reorganization (adding
v1prefix), type moves between modules, class renames, method renames, and Gradle dependency updates. Some changes require manual intervention and are not covered by this recipe:Table.uuid()should be changed toTable.javaUUID()forjava.util.UUIDvalues,DateColumnTypewith constructor parametertime=falseortime=trueshould be split intoJodaLocalDateColumnTypeorJodaLocalDateTimeColumnType,SqlExpressionBuilder.*usages should be replaced with top-level function imports, andStatement.execute()calls should useBlockingExecutablewrapping.
- org.openrewrite.kotlin.kotlinx.ReplaceDeprecatedKotlinxMethods
- Replace deprecated
kotlinxmethods - Replace deprecated Kotlin extension library method calls with their recommended replacements, based on
@Deprecated(replaceWith=ReplaceWith(...))annotations.
- Replace deprecated
- org.openrewrite.kotlin.migrate.RemoveDeprecatedKotlinGradleProperties
- Remove deprecated Kotlin Gradle properties
- Remove deprecated Kotlin Gradle properties from
gradle.properties.kotlin.experimental.coroutineswas removed in Kotlin 2.x.
- org.openrewrite.kotlin.migrate.RemoveRedundantKotlinStdlib
- Remove redundant kotlin-stdlib dependencies
- Remove explicit
kotlin-stdlib,kotlin-stdlib-jdk7,kotlin-stdlib-jdk8, andkotlin-stdlib-commondependencies. The Kotlin Gradle plugin has automatically included the stdlib since Kotlin 1.4, making explicit declarations redundant.
- org.openrewrite.kotlin.migrate.ReplaceDeprecatedAppendln
- Replace deprecated
appendlnwithappendLine - Replace
appendln()withappendLine(). This was deprecated in Kotlin 1.4 and becomes an error in Kotlin 2.1.
- Replace deprecated
- org.openrewrite.kotlin.migrate.ReplaceDeprecatedCapitalizeAndDecapitalize
- Replace deprecated
capitalizeanddecapitalize - Replace
String.capitalize()withString.replaceFirstChar \{ if (it.isLowerCase()) it.titlecase() else it.toString() \}andString.decapitalize()withString.replaceFirstChar \{ it.lowercase() \}. These were deprecated in Kotlin 1.5 and become errors in Kotlin 2.1.
- Replace deprecated
- org.openrewrite.kotlin.migrate.ReplaceDeprecatedCharCaseConversions
- Replace deprecated Char case conversions
- Replace
Char.toLowerCase()withChar.lowercaseChar()andChar.toUpperCase()withChar.uppercaseChar(). These were deprecated in Kotlin 1.5 and become errors in Kotlin 2.1.
- org.openrewrite.kotlin.migrate.ReplaceDeprecatedStringCaseConversions
- Replace deprecated String case conversions
- Replace
String.toLowerCase()withString.lowercase()andString.toUpperCase()withString.uppercase(). These were deprecated in Kotlin 1.5 and become errors in Kotlin 2.1.
- org.openrewrite.kotlin.migrate.ReplaceEnumValuesFunctionWithEnumEntries
- Replace
enumValues<T>()withenumEntries<T>() - Replace calls to
enumValues<T>()withenumEntries<T>(). TheenumEntriesfunction returns an efficient immutable list instead of creating a new array. Deprecated since Kotlin 1.9, recommended replacement for Kotlin 2.x.
- Replace
- org.openrewrite.kotlin.migrate.ReplaceEnumValuesWithEntries
- Replace
Enum.values()withEnum.entries - Replace calls to
Enum.values()with theEnum.entriesproperty. Theentriesproperty returns an efficient immutable list instead of creating a new array on each call. Deprecated since Kotlin 1.9, recommended replacement for Kotlin 2.x.
- Replace
- org.openrewrite.kotlin.migrate.ReplaceKotlinOptionsWithCompilerOptions
- Replace
kotlinOptionswithcompilerOptionsin Gradle build files - Rename the deprecated
kotlinOptionsDSL block tocompilerOptionsin Gradle build files. ThekotlinOptionsDSL was deprecated in Kotlin 2.0 and removed in Kotlin 2.2.
- Replace
- org.openrewrite.kotlin.migrate.UpgradeKotlinGradlePlugins
- Upgrade Kotlin Gradle plugins to 2.x
- Upgrade all
org.jetbrains.kotlin.*Gradle plugins to Kotlin 2.x. This includes the core kotlin-jvm plugin as well as all official Kotlin Gradle plugins such as serialization, Spring, allopen, noarg, JPA, and parcelize.
- org.openrewrite.kotlin.migrate.UpgradeKotlinxCoroutines_1_10
- Upgrade to
kotlinx-coroutines1.10 - Upgrade kotlinx-coroutines to 1.10.x and replace deprecated method calls.
- Upgrade to
- org.openrewrite.kotlin.migrate.UpgradeKotlinxDatetime_0_7
- Migrate to
kotlinx-datetime0.7 - Migrate from kotlinx-datetime 0.6.x to 0.7.x. This includes replacing
kotlinx.datetime.Instantandkotlinx.datetime.Clockwith theirkotlin.timeequivalents and replacing deprecated method calls.
- Migrate to
- org.openrewrite.kotlin.migrate.UpgradeKotlinxSerialization_1_8
- Upgrade to
kotlinx-serialization1.8 - Upgrade kotlinx-serialization to 1.8.x and replace deprecated method calls.
- Upgrade to
- org.openrewrite.kotlin.migrate.UpgradeToKotlin2
- Migrate to Kotlin 2
- Migrate deprecated Kotlin 1.x APIs to their Kotlin 2.x replacements and update Gradle build files for Kotlin 2.x compatibility. Deprecated APIs were deprecated in Kotlin 1.4-1.5 and become errors in Kotlin 2.1.
- org.openrewrite.kotlin.replace.ReplaceKotlinMethod
- Replace Kotlin method
- Replaces Kotlin method calls based on
@Deprecated(replaceWith=ReplaceWith(...))annotations.
rewrite-migrate-python
- org.openrewrite.python.codequality.AllBranchesIdentical
- Remove conditional with identical branches
- Replace
if/elif/elsechains where every branch has the same body with just the body, since the condition has no effect on what code executes.
- org.openrewrite.python.codequality.BooleanChecksNotInverted
- Boolean checks should not be inverted
- Replace inverted boolean comparisons like
not (a == b)with the equivalent direct operator (a != b), and remove double negations likenot (not x).
- org.openrewrite.python.codequality.CollapsibleIfStatements
- Merge collapsible if statements
- Combine nested
ifstatements that have noelsebranch into a singleifjoined withand.
- org.openrewrite.python.codequality.MergeIdenticalBranches
- Merge consecutive branches with identical bodies
- Combine consecutive
if/elifbranches that have the same body into a single branch with conditions joined byor.
- org.openrewrite.python.codequality.RemoveDuplicateConditions
- Remove duplicate conditions in if/elif chains
- Remove
elifbranches whose condition is identical to an earlier branch in the sameif/elifchain, since the duplicate branch is dead code that can never execute.
- org.openrewrite.python.codequality.RemoveSelfAssignment
- Remove self-assignments
- Remove statements that assign a variable to itself (
x = x,self.x = self.x), since they have no effect.
- org.openrewrite.python.codequality.RemoveUnconditionalValueOverwrite
- Remove unconditional value overwrites
- Remove consecutive assignments that write to the same dict key or object attribute, since the first value is immediately overwritten and never used.
- org.openrewrite.python.codequality.SimplifyBooleanLiteral
- Simplify boolean literal comparisons
- Replace comparisons against boolean literals (
== True,!= False,is True, etc.) with the simpler equivalent boolean expression.
- org.openrewrite.python.codequality.SimplifyRedundantLogicalExpression
- Simplify redundant logical expressions
- Replace
x and xwithxandx or xwithx. Identical operands in a logical expression are redundant and often indicate a copy-paste mistake.
- org.openrewrite.python.migrate.DependencyInsight
- Python dependency insight
- Find Python dependencies, including transitive dependencies, matching a package name pattern. Results include the resolved version, scope, and whether the dependency is direct or transitive.
- org.openrewrite.python.migrate.FindAifcModule
- Find deprecated
aifcmodule usage - The
aifcmodule was deprecated in Python 3.11 and removed in Python 3.13. Use third-party audio libraries instead.
- Find deprecated
- org.openrewrite.python.migrate.FindAsyncioCoroutineDecorator
- Find deprecated
@asyncio.coroutinedecorator - Find usage of the deprecated
@asyncio.coroutinedecorator which was removed in Python 3.11. Convert toasync defsyntax withawaitinstead ofyield from.
- Find deprecated
- org.openrewrite.python.migrate.FindAudioopModule
- Find deprecated
audioopmodule usage - The
audioopmodule was deprecated in Python 3.11 and removed in Python 3.13. Use pydub, numpy, or scipy for audio operations.
- Find deprecated
- org.openrewrite.python.migrate.FindCgiModule
- Find deprecated
cgimodule usage - The
cgimodule was deprecated in Python 3.11 and removed in Python 3.13. Useurllib.parsefor query string parsing,html.escape()for escaping, and web frameworks oremail.messagefor form handling.
- Find deprecated
- org.openrewrite.python.migrate.FindCgitbModule
- Find deprecated
cgitbmodule usage - The
cgitbmodule was deprecated in Python 3.11 and removed in Python 3.13. Use the standardloggingandtracebackmodules for error handling.
- Find deprecated
- org.openrewrite.python.migrate.FindChunkModule
- Find deprecated
chunkmodule usage - The
chunkmodule was deprecated in Python 3.11 and removed in Python 3.13. Implement IFF chunk reading manually or use specialized libraries.
- Find deprecated
- org.openrewrite.python.migrate.FindCryptModule
- Find deprecated
cryptmodule usage - The
cryptmodule was deprecated in Python 3.11 and removed in Python 3.13. Usebcrypt,argon2-cffi, orpasslibinstead.
- Find deprecated
- org.openrewrite.python.migrate.FindDistutilsUsage
- Find deprecated distutils module usage
- Find imports of the deprecated
distutilsmodule which was removed in Python 3.12. Migrate tosetuptoolsor other modern build tools.
- org.openrewrite.python.migrate.FindFunctoolsCmpToKey
- Find
functools.cmp_to_key()usage - Find usage of
functools.cmp_to_key()which is a Python 2 compatibility function. Consider using a key function directly.
- Find
- org.openrewrite.python.migrate.FindFutureImports
- Find
__future__imports - Find
__future__imports and add a search marker.
- Find
- org.openrewrite.python.migrate.FindImghdrModule
- Find deprecated
imghdrmodule usage - The
imghdrmodule was deprecated in Python 3.11 and removed in Python 3.13. Usefiletype,python-magic, orPillowinstead.
- Find deprecated
- org.openrewrite.python.migrate.FindImpUsage
- Find deprecated imp module usage
- Find imports of the deprecated
impmodule which was removed in Python 3.12. Migrate toimportlib.
- org.openrewrite.python.migrate.FindLocaleGetdefaultlocale
- Find deprecated
locale.getdefaultlocale()usage locale.getdefaultlocale()was deprecated in Python 3.11. Uselocale.setlocale(),locale.getlocale(), orlocale.getpreferredencoding(False)instead.
- Find deprecated
- org.openrewrite.python.migrate.FindMacpathModule
- Find removed
macpathmodule usage - The
macpathmodule was removed in Python 3.8. Useos.pathinstead.
- Find removed
- org.openrewrite.python.migrate.FindMailcapModule
- Find deprecated
mailcapmodule usage - The
mailcapmodule was deprecated in Python 3.11 and removed in Python 3.13. Usemimetypesmodule for MIME type handling.
- Find deprecated
- org.openrewrite.python.migrate.FindMethods
- Find Python function and method usages
- Find function and method calls by pattern. Covers standalone functions, class methods, static methods, and constructor calls.
- org.openrewrite.python.migrate.FindMsilibModule
- Find deprecated
msilibmodule usage - The
msilibmodule was deprecated in Python 3.11 and removed in Python 3.13. Use platform-specific tools for MSI creation.
- Find deprecated
- org.openrewrite.python.migrate.FindNisModule
- Find deprecated
nismodule usage - The
nismodule was deprecated in Python 3.11 and removed in Python 3.13. There is no direct replacement.
- Find deprecated
- org.openrewrite.python.migrate.FindNntplibModule
- Find deprecated
nntplibmodule usage - The
nntplibmodule was deprecated in Python 3.11 and removed in Python 3.13. NNTP is largely obsolete; consider alternatives if needed.
- Find deprecated
- org.openrewrite.python.migrate.FindOsPopen
- Find deprecated
os.popen()usage os.popen()has been deprecated since Python 3.6. Usesubprocess.run()orsubprocess.Popen()instead for better control over process creation and output handling.
- Find deprecated
- org.openrewrite.python.migrate.FindOsSpawn
- Find deprecated
os.spawn*()usage - The
os.spawn*()family of functions are deprecated. Usesubprocess.run()orsubprocess.Popen()instead.
- Find deprecated
- org.openrewrite.python.migrate.FindOssaudiodevModule
- Find deprecated
ossaudiodevmodule usage - The
ossaudiodevmodule was deprecated in Python 3.11 and removed in Python 3.13. There is no direct replacement.
- Find deprecated
- org.openrewrite.python.migrate.FindPathlibLinkTo
- Find deprecated
Path.link_to()usage - Find usage of
Path.link_to()which was deprecated in Python 3.10 and removed in 3.12. Usehardlink_to()instead (note: argument order is reversed).
- Find deprecated
- org.openrewrite.python.migrate.FindPipesModule
- Find deprecated
pipesmodule usage - The
pipesmodule was deprecated in Python 3.11 and removed in Python 3.13. Use subprocess with shlex.quote() for shell escaping.
- Find deprecated
- org.openrewrite.python.migrate.FindRemovedModules312
- Find modules removed in Python 3.12
- Find imports of modules that were removed in Python 3.12, including asynchat, asyncore, and smtpd.
- org.openrewrite.python.migrate.FindShutilRmtreeOnerror
- Find deprecated
shutil.rmtree(onerror=...)parameter - The
onerrorparameter ofshutil.rmtree()was deprecated in Python 3.12 in favor ofonexc. Theonexccallback receives the exception object directly rather than an exc_info tuple.
- Find deprecated
- org.openrewrite.python.migrate.FindSndhdrModule
- Find deprecated
sndhdrmodule usage - The
sndhdrmodule was deprecated in Python 3.11 and removed in Python 3.13. Usefiletypeor audio libraries likepydubinstead.
- Find deprecated
- org.openrewrite.python.migrate.FindSocketGetFQDN
- Find
socket.getfqdn()usage - Find usage of
socket.getfqdn()which can be slow and unreliable. Consider usingsocket.gethostname()instead.
- Find
- org.openrewrite.python.migrate.FindSpwdModule
- Find deprecated
spwdmodule usage - The
spwdmodule was deprecated in Python 3.11 and removed in Python 3.13. There is no direct replacement.
- Find deprecated
- org.openrewrite.python.migrate.FindSslMatchHostname
- Find deprecated
ssl.match_hostname() - Find usage of the deprecated
ssl.match_hostname()function which was removed in Python 3.12. Usessl.SSLContext.check_hostnameinstead.
- Find deprecated
- org.openrewrite.python.migrate.FindSunauModule
- Find deprecated
sunaumodule usage - The
sunaumodule was deprecated in Python 3.11 and removed in Python 3.13. Usesoundfileorpydubinstead.
- Find deprecated
- org.openrewrite.python.migrate.FindSysCoroutineWrapper
- Find removed
sys.set_coroutine_wrapper()/sys.get_coroutine_wrapper() sys.set_coroutine_wrapper()andsys.get_coroutine_wrapper()were deprecated in Python 3.7 and removed in Python 3.8.
- Find removed
- org.openrewrite.python.migrate.FindTelnetlibModule
- Find deprecated
telnetlibmodule usage - The
telnetlibmodule was deprecated in Python 3.11 and removed in Python 3.13. Consider usingtelnetlib3from PyPI, direct socket usage, or SSH-based alternatives like paramiko.
- Find deprecated
- org.openrewrite.python.migrate.FindTempfileMktemp
- Find deprecated
tempfile.mktemp()usage - Find usage of
tempfile.mktemp()which is deprecated due to security concerns (race condition). Usemkstemp()orNamedTemporaryFile()instead.
- Find deprecated
- org.openrewrite.python.migrate.FindTypes
- Find Python types
- Find type references by name. Identifies classes matching a type pattern. In Python, all type definitions use the
classkeyword, covering regular classes, abstract base classes, protocols, enums, dataclasses, named tuples, typed dicts, and more.
- org.openrewrite.python.migrate.FindUrllibParseSplitFunctions
- Find deprecated urllib.parse split functions
- Find usage of deprecated urllib.parse split functions (splithost, splitport, etc.) removed in Python 3.14. Use urlparse() instead.
- org.openrewrite.python.migrate.FindUrllibParseToBytes
- Find deprecated
urllib.parse.to_bytes()usage - Find usage of
urllib.parse.to_bytes()which was deprecated in Python 3.8 and removed in 3.14. Use str.encode() directly.
- Find deprecated
- org.openrewrite.python.migrate.FindUuModule
- Find deprecated
uumodule usage - The
uumodule was deprecated in Python 3.11 and removed in Python 3.13. Usebase64module instead for encoding binary data.
- Find deprecated
- org.openrewrite.python.migrate.FindXdrlibModule
- Find deprecated
xdrlibmodule usage - The
xdrlibmodule was deprecated in Python 3.11 and removed in Python 3.13. Usestructmodule for binary packing/unpacking.
- Find deprecated
- org.openrewrite.python.migrate.MigrateAsyncioCoroutine
- Migrate
@asyncio.coroutinetoasync def - Migrate functions using the deprecated
@asyncio.coroutinedecorator to useasync defsyntax. Also transformsyield fromtoawait. The decorator was removed in Python 3.11.
- Migrate
- org.openrewrite.python.migrate.MigrateToPyprojectToml
- Migrate to
pyproject.toml - Migrate Python projects from
requirements.txtand/orsetup.cfgtopyproject.tomlwithhatchlingbuild backend.
- Migrate to
- org.openrewrite.python.migrate.RemoveFutureImports
- Remove obsolete
__future__imports - Remove
from __future__ import ...statements for features that are enabled by default in Python 3.
- Remove obsolete
- org.openrewrite.python.migrate.ReplaceArrayFromstring
- Replace
array.fromstring()witharray.frombytes() - Replace
fromstring()withfrombytes()on array objects. The fromstring() method was deprecated in Python 3.2 and removed in 3.14.
- Replace
- org.openrewrite.python.migrate.ReplaceArrayTostring
- Replace
array.tostring()witharray.tobytes() - Replace
tostring()withtobytes()on array objects. The tostring() method was deprecated in Python 3.2 and removed in 3.14.
- Replace
- org.openrewrite.python.migrate.ReplaceAstBytes
- Replace
ast.Byteswithast.Constant - The
ast.Bytesnode type was deprecated in Python 3.8 and removed in Python 3.14. Replace withast.Constantand checkisinstance(node.value, bytes).
- Replace
- org.openrewrite.python.migrate.ReplaceAstEllipsis
- Replace
ast.Ellipsiswithast.Constant - The
ast.Ellipsisnode type was deprecated in Python 3.8 and removed in Python 3.14. Replace withast.Constantand checknode.value is ....
- Replace
- org.openrewrite.python.migrate.ReplaceAstNameConstant
- Replace
ast.NameConstantwithast.Constant - The
ast.NameConstantnode type was deprecated in Python 3.8 and removed in Python 3.14. Replace withast.Constantand checknode.value in (True, False, None).
- Replace
- org.openrewrite.python.migrate.ReplaceAstNum
- Replace
ast.Numwithast.Constant - The
ast.Numnode type was deprecated in Python 3.8 and removed in Python 3.14. Replace withast.Constantand checkisinstance(node.value, (int, float, complex)).
- Replace
- org.openrewrite.python.migrate.ReplaceAstStr
- Replace
ast.Strwithast.Constant - The
ast.Strnode type was deprecated in Python 3.8 and removed in Python 3.14. Replace withast.Constantand checkisinstance(node.value, str).
- Replace
- org.openrewrite.python.migrate.ReplaceCalendarConstants
- Replace deprecated calendar constants with uppercase
- Replace deprecated mixed-case calendar constants like
calendar.Januarywith their uppercase equivalents likecalendar.JANUARY. The mixed-case constants were deprecated in Python 3.12.
- org.openrewrite.python.migrate.ReplaceCgiParseQs
- Replace
cgi.parse_qs()withurllib.parse.parse_qs() cgi.parse_qs()was removed in Python 3.8. Useurllib.parse.parse_qs()instead. Note: this rewrites call sites but does not manage imports. Use withChangeImportin a composite recipe to updatefromimports.
- Replace
- org.openrewrite.python.migrate.ReplaceCgiParseQsl
- Replace
cgi.parse_qsl()withurllib.parse.parse_qsl() cgi.parse_qsl()was removed in Python 3.8. Useurllib.parse.parse_qsl()instead. Note: this rewrites call sites but does not manage imports. Use withChangeImportin a composite recipe to updatefromimports.
- Replace
- org.openrewrite.python.migrate.ReplaceCollectionsAbcImports
- Replace
collectionsABC imports withcollections.abc - Migrate deprecated abstract base class imports from
collectionstocollections.abc. These imports were deprecated in Python 3.3 and removed in Python 3.10.
- Replace
- org.openrewrite.python.migrate.ReplaceConditionNotifyAll
- Replace
Condition.notifyAll()withCondition.notify_all() - Replace
notifyAll()method calls withnotify_all(). The camelCase version was deprecated in Python 3.10 and removed in 3.12.
- Replace
- org.openrewrite.python.migrate.ReplaceConfigparserReadfp
- Replace
ConfigParser.readfp()withread_file() - The
ConfigParser.readfp()method was deprecated in Python 3.2 and removed in Python 3.13. Replace withread_file().
- Replace
- org.openrewrite.python.migrate.ReplaceConfigparserSafeConfigParser
- Replace
configparser.SafeConfigParserwithConfigParser - The
configparser.SafeConfigParserclass was deprecated in Python 3.2 and removed in Python 3.12. Replace withconfigparser.ConfigParser.
- Replace
- org.openrewrite.python.migrate.ReplaceDatetimeUtcFromTimestamp
- Replace
datetime.utcfromtimestamp()withdatetime.fromtimestamp(ts, UTC) - The
datetime.utcfromtimestamp()method is deprecated in Python 3.12. Replace it withdatetime.fromtimestamp(ts, datetime.UTC)for timezone-aware datetime objects.
- Replace
- org.openrewrite.python.migrate.ReplaceDatetimeUtcNow
- Replace
datetime.utcnow()withdatetime.now(UTC) - The
datetime.utcnow()method is deprecated in Python 3.12. Replace it withdatetime.now(datetime.UTC)for timezone-aware datetime objects.
- Replace
- org.openrewrite.python.migrate.ReplaceDistutilsVersion
- Replace deprecated distutils.version usage
- Detect usage of deprecated
distutils.version.LooseVersionanddistutils.version.StrictVersion. These should be migrated topackaging.version.Version. Note: Manual migration is required aspackaging.version.Versionis not a drop-in replacement.
- org.openrewrite.python.migrate.ReplaceElementGetchildren
- Replace
Element.getchildren()withlist(element) - Replace
getchildren()withlist(element)on XML Element objects. Deprecated in Python 3.9.
- Replace
- org.openrewrite.python.migrate.ReplaceElementGetiterator
- Replace
Element.getiterator()withElement.iter() - Replace
getiterator()withiter()on XML Element objects. The getiterator() method was deprecated in Python 3.9.
- Replace
- org.openrewrite.python.migrate.ReplaceEventIsSet
- Replace
Event.isSet()withEvent.is_set() - Replace
isSet()method calls withis_set(). The camelCase version was deprecated in Python 3.10 and removed in 3.12.
- Replace
- org.openrewrite.python.migrate.ReplaceGettextDeprecations
- Replace deprecated gettext l*gettext() functions
- Replace deprecated gettext functions like
lgettext()with their modern equivalents likegettext(). The l*gettext() functions were removed in Python 3.11.
- org.openrewrite.python.migrate.ReplaceHtmlParserUnescape
- Replace
HTMLParser.unescape()withhtml.unescape() HTMLParser.unescape()was removed in Python 3.9. Usehtml.unescape()instead.
- Replace
- org.openrewrite.python.migrate.ReplaceLocaleResetlocale
- Replace
locale.resetlocale()withlocale.setlocale(LC_ALL, '') - The
locale.resetlocale()function was deprecated in Python 3.11 and removed in Python 3.13. Replace withlocale.setlocale(locale.LC_ALL, '').
- Replace
- org.openrewrite.python.migrate.ReplacePercentFormatWithFString
- Replace
%formatting with f-string - Replace
"..." % (...)expressions with f-strings (Python 3.6+). Only converts%sand%rspecifiers where the format string is a literal and the conversion is safe.
- Replace
- org.openrewrite.python.migrate.ReplacePkgutilFindLoader
- Replace
pkgutil.find_loader()withimportlib.util.find_spec() - The
pkgutil.find_loader()function was deprecated in Python 3.12. Replace withimportlib.util.find_spec(). Note: returns ModuleSpec, use .loader for loader.
- Replace
- org.openrewrite.python.migrate.ReplacePkgutilGetLoader
- Replace
pkgutil.get_loader()withimportlib.util.find_spec() - The
pkgutil.get_loader()function was deprecated in Python 3.12. Replace withimportlib.util.find_spec(). Note: returns ModuleSpec, use .loader for loader.
- Replace
- org.openrewrite.python.migrate.ReplacePlatformPopen
- Replace
platform.popen()withsubprocess.check_output() platform.popen()was removed in Python 3.8. Usesubprocess.check_output(cmd, shell=True)instead. Note: this rewrites call sites but does not manage imports.
- Replace
- org.openrewrite.python.migrate.ReplaceReTemplate
- Replace
re.template()withre.compile()and flagre.TEMPLATE/re.T re.template()was deprecated in Python 3.11 and removed in 3.13. Calls are auto-replaced withre.compile().re.TEMPLATE/re.Tflags have no direct replacement and are flagged for manual review.
- Replace
- org.openrewrite.python.migrate.ReplaceStrFormatWithFString
- Replace
str.format()with f-string - Replace
"...".format(...)calls with f-strings (Python 3.6+). Only converts cases where the format string is a literal and the conversion is safe.
- Replace
- org.openrewrite.python.migrate.ReplaceSysLastExcInfo
- Replace
sys.last_valuewithsys.last_excand flagsys.last_type/sys.last_traceback sys.last_type,sys.last_value, andsys.last_tracebackwere deprecated in Python 3.12.sys.last_valueis auto-replaced withsys.last_exc;sys.last_typeandsys.last_tracebackare flagged for manual review.
- Replace
- org.openrewrite.python.migrate.ReplaceTarfileFilemode
- Replace
tarfile.filemodewithstat.filemode tarfile.filemodewas removed in Python 3.8. Usestat.filemode()instead.
- Replace
- org.openrewrite.python.migrate.ReplaceThreadGetName
- Replace
Thread.getName()withThread.name - Replace
getName()method calls with thenameproperty. Deprecated in Python 3.10, removed in 3.12.
- Replace
- org.openrewrite.python.migrate.ReplaceThreadIsAlive
- Replace
Thread.isAlive()withThread.is_alive() - Replace
isAlive()method calls withis_alive(). Deprecated in Python 3.1 and removed in 3.9.
- Replace
- org.openrewrite.python.migrate.ReplaceThreadIsDaemon
- Replace
Thread.isDaemon()withThread.daemon - Replace
isDaemon()method calls with thedaemonproperty. Deprecated in Python 3.10, removed in 3.12.
- Replace
- org.openrewrite.python.migrate.ReplaceThreadSetDaemon
- Replace
Thread.setDaemon()withThread.daemon = ... - Replace
setDaemon()method calls withdaemonproperty assignment. Deprecated in Python 3.10, removed in 3.12.
- Replace
- org.openrewrite.python.migrate.ReplaceThreadSetName
- Replace
Thread.setName()withThread.name = ... - Replace
setName()method calls withnameproperty assignment. Deprecated in Python 3.10, removed in 3.12.
- Replace
- org.openrewrite.python.migrate.ReplaceThreadingActiveCount
- Replace
threading.activeCount()withthreading.active_count() - Replace
threading.activeCount()withthreading.active_count(). The camelCase version was deprecated in Python 3.10 and removed in 3.12.
- Replace
- org.openrewrite.python.migrate.ReplaceThreadingCurrentThread
- Replace
threading.currentThread()withthreading.current_thread() - Replace
threading.currentThread()withthreading.current_thread(). The camelCase version was deprecated in Python 3.10 and removed in 3.12.
- Replace
- org.openrewrite.python.migrate.ReplaceTypingCallableWithCollectionsAbcCallable
- Replace
typing.Callablewithcollections.abc.Callable - PEP 585 deprecated
typing.Callablein Python 3.9. Replace withcollections.abc.Callablefor type annotations.
- Replace
- org.openrewrite.python.migrate.ReplaceTypingDictWithDict
- Replace
typing.Dictwithdict - PEP 585 deprecated
typing.Dictin Python 3.9. Replace with the built-indicttype for generic annotations.
- Replace
- org.openrewrite.python.migrate.ReplaceTypingListWithList
- Replace
typing.Listwithlist - PEP 585 deprecated
typing.Listin Python 3.9. Replace with the built-inlisttype for generic annotations.
- Replace
- org.openrewrite.python.migrate.ReplaceTypingOptionalWithUnion
- Replace
typing.Optional[X]withX | None - PEP 604 introduced the
|operator for union types in Python 3.10. ReplaceOptional[X]with the more conciseX | Nonesyntax.
- Replace
- org.openrewrite.python.migrate.ReplaceTypingSetWithSet
- Replace
typing.Setwithset - PEP 585 deprecated
typing.Setin Python 3.9. Replace with the built-insettype for generic annotations.
- Replace
- org.openrewrite.python.migrate.ReplaceTypingText
- Replace
typing.Textwithstr typing.Textis deprecated as of Python 3.11. It was an alias forstrfor Python 2/3 compatibility. Replace withstr.
- Replace
- org.openrewrite.python.migrate.ReplaceTypingTupleWithTuple
- Replace
typing.Tuplewithtuple - PEP 585 deprecated
typing.Tuplein Python 3.9. Replace with the built-intupletype for generic annotations.
- Replace
- org.openrewrite.python.migrate.ReplaceTypingUnionWithPipe
- Replace
typing.Union[X, Y]withX | Y - PEP 604 introduced the
|operator for union types in Python 3.10. ReplaceUnion[X, Y, ...]with the more conciseX | Y | ...syntax.
- Replace
- org.openrewrite.python.migrate.ReplaceUnittestDeprecatedAliases
- Replace deprecated unittest method aliases
- Replace deprecated unittest.TestCase method aliases like
assertEqualswith their modern equivalents likeassertEqual. These aliases were removed in Python 3.11/3.12.
- org.openrewrite.python.migrate.UpgradeToPython310
- Upgrade to Python 3.10
- Migrate deprecated APIs and adopt new syntax for Python 3.10 compatibility. This includes adopting PEP 604 union type syntax (
X | Y) and other modernizations between Python 3.9 and 3.10.
- org.openrewrite.python.migrate.UpgradeToPython311
- Upgrade to Python 3.11
- Migrate deprecated and removed APIs for Python 3.11 compatibility. This includes handling removed modules, deprecated functions, and API changes between Python 3.10 and 3.11.
- org.openrewrite.python.migrate.UpgradeToPython312
- Upgrade to Python 3.12
- Migrate deprecated and removed APIs for Python 3.12 compatibility. This includes detecting usage of the removed
impmodule and other legacy modules that were removed in Python 3.12.
- org.openrewrite.python.migrate.UpgradeToPython313
- Upgrade to Python 3.13
- Migrate deprecated and removed APIs for Python 3.13 compatibility. This includes detecting usage of modules removed in PEP 594 ('dead batteries') and other API changes between Python 3.12 and 3.13.
- org.openrewrite.python.migrate.UpgradeToPython314
- Upgrade to Python 3.14
- Migrate deprecated and removed APIs for Python 3.14 compatibility. This includes replacing deprecated AST node types with
ast.Constantand other API changes between Python 3.13 and 3.14.
- org.openrewrite.python.migrate.UpgradeToPython38
- Upgrade to Python 3.8
- Migrate deprecated APIs and detect legacy patterns for Python 3.8 compatibility.
- org.openrewrite.python.migrate.UpgradeToPython39
- Upgrade to Python 3.9
- Migrate deprecated APIs for Python 3.9 compatibility. This includes PEP 585 built-in generics, removed base64 functions, and deprecated XML Element methods.
- org.openrewrite.python.migrate.langchain.FindDeprecatedLangchainAgents
- Find deprecated LangChain agent patterns
- Find usage of deprecated LangChain agent patterns including
initialize_agent,AgentExecutor, andLLMChain. These were deprecated in LangChain v0.2 and removed in v1.0.
- org.openrewrite.python.migrate.langchain.FindLangchainCreateReactAgent
- Find
create_react_agentusage (replace withcreate_agent) - Find
from langgraph.prebuilt import create_react_agentwhich should be replaced withfrom langchain.agents import create_agentin LangChain v1.0.
- Find
- org.openrewrite.python.migrate.langchain.ReplaceLangchainClassicImports
- Replace
langchainlegacy imports withlangchain_classic - Migrate legacy chain, retriever, and indexing imports from
langchaintolangchain_classic. These were moved in LangChain v1.0.
- Replace
- org.openrewrite.python.migrate.langchain.ReplaceLangchainCommunityImports
- Replace
langchainimports withlangchain_community - Migrate third-party integration imports from
langchaintolangchain_community. These integrations were moved in LangChain v0.2.
- Replace
- org.openrewrite.python.migrate.langchain.ReplaceLangchainProviderImports
- Replace
langchain_communityimports with provider packages - Migrate provider-specific imports from
langchain_communityto dedicated provider packages likelangchain_openai,langchain_anthropic, etc.
- Replace
- org.openrewrite.python.migrate.langchain.UpgradeToLangChain02
- Upgrade to LangChain 0.2
- Migrate to LangChain 0.2 by updating imports from
langchaintolangchain_communityand provider-specific packages.
- org.openrewrite.python.migrate.langchain.UpgradeToLangChain1
- Upgrade to LangChain 1.0
- Migrate to LangChain 1.0 by applying all v0.2 migrations and then moving legacy functionality to
langchain_classic.
rewrite-nodejs
- org.openrewrite.node.dependency-vulnerability-check
- Find and fix vulnerable npm dependencies
- This software composition analysis (SCA) tool detects and upgrades dependencies with publicly disclosed vulnerabilities. This recipe both generates a report of vulnerable dependencies and upgrades to newer versions with fixes. This recipe by default only upgrades to the latest patch version. If a minor or major upgrade is required to reach the fixed version, this can be controlled using the
maximumUpgradeDeltaoption. Vulnerability information comes from the GitHub Security Advisory Database, which aggregates vulnerability data from several public databases, including the National Vulnerability Database maintained by the United States government. ## Customizing Vulnerability Data This recipe can be customized by extendingDependencyVulnerabilityCheckand overriding the vulnerability data sources: -baselineVulnerabilities(ctx): Provides the default set of known vulnerabilities. The base implementation loads vulnerability data from the GitHub Security Advisory Database CSV file. Override this method to replace the entire vulnerability dataset with your own curated list. -supplementalVulnerabilities(ctx): Allows adding custom vulnerability data beyond the baseline. The base implementation returns an empty list. Override this method to add organization-specific vulnerabilities, internal security advisories, or vulnerabilities from additional sources while retaining the baseline GitHub Advisory Database. Both methods returnVulnerability[]arrays. Vulnerability data can be loaded from CSV files usingVulnerabilityDatabase.loadFromFile(path).getAllVulnerabilities()or constructed programmatically. For example, overridesupplementalVulnerabilities()to add custom CVEs while keeping the standard vulnerability database, or overridebaselineVulnerabilities()to use an entirely different vulnerability data source.
- org.openrewrite.node.migrate.buffer.replace-deprecated-slice
- Replace deprecated
Buffer.slice()withBuffer.subarray() - Replace deprecated
buffer.slice()calls withbuffer.subarray()for compatibility with Uint8Array.prototype.slice().
- Replace deprecated
- org.openrewrite.node.migrate.buffer.replace-slow-buffer
- Replace deprecated
SlowBufferwithBuffer.allocUnsafeSlow() - Replace deprecated
new SlowBuffer(size)calls withBuffer.allocUnsafeSlow(size). SlowBuffer was used to create un-pooled Buffer instances, but has been removed in favor of the explicit Buffer.allocUnsafeSlow() method.
- Replace deprecated
- org.openrewrite.node.migrate.crypto.find-create-cipher
- Find deprecated
crypto.createCipher()andcrypto.createDecipher()usage crypto.createCipher()andcrypto.createDecipher()were deprecated in Node.js 10 (DEP0106) and removed in Node.js 22. Usecrypto.createCipheriv()andcrypto.createDecipheriv()instead.
- Find deprecated
- org.openrewrite.node.migrate.crypto.replace-crypto-fips
- Replace deprecated
crypto.fipswithcrypto.getFips()andcrypto.setFips() - Replace deprecated
crypto.fipsproperty access withcrypto.getFips()for reads andcrypto.setFips(value)for writes.
- Replace deprecated
- org.openrewrite.node.migrate.crypto.replace-hash-constructor
- Replace deprecated
new crypto.Hash()andnew crypto.Hmac()with factory methods - Replace deprecated
new crypto.Hash(algorithm)constructor calls withcrypto.createHash(algorithm)andnew crypto.Hmac(algorithm, key)withcrypto.createHmac(algorithm, key)factory methods.
- Replace deprecated
- org.openrewrite.node.migrate.find-process-assert
- Find deprecated
process.assert()usage process.assert()was deprecated in Node.js 10 (DEP0100) and removed in Node.js 23. Use theassertmodule instead.
- Find deprecated
- org.openrewrite.node.migrate.find-punycode-usage
- Find deprecated
punycodemodule usage - The
punycodebuilt-in module was deprecated in Node.js 21 (DEP0040). Use the userlandpunycodepackage from npm orurl.domainToASCII/url.domainToUnicodeinstead.
- Find deprecated
- org.openrewrite.node.migrate.fs.replace-dirent-path
- Replace
dirent.pathwithdirent.parentPath - Replaces deprecated
dirent.pathproperty access withdirent.parentPathonfs.Direntinstances to address DEP0178 deprecation.
- Replace
- org.openrewrite.node.migrate.fs.replace-fs-access-constants
- Replace deprecated
fs.F_OK,fs.R_OK,fs.W_OK,fs.X_OKwithfs.constants.* - Replace deprecated file access constants (
fs.F_OK,fs.R_OK,fs.W_OK,fs.X_OK) with their equivalents fromfs.constants. These constants were removed in Node.js v24+ and should be accessed through the constants namespace.
- Replace deprecated
- org.openrewrite.node.migrate.fs.replace-fs-truncate-fd
- Replace
fs.truncate()with file descriptor tofs.ftruncate() - Replace deprecated
fs.truncate(fd, ...)andfs.truncateSync(fd, ...)calls withfs.ftruncate(fd, ...)andfs.ftruncateSync(fd, ...)when the first argument is a file descriptor (number).
- Replace
- org.openrewrite.node.migrate.fs.replace-stats-constructor
- Replace deprecated
fs.Statsconstructor with object literal - Replace deprecated
new fs.Stats()constructor calls with an object literal containing Stats properties initialized to undefined.
- Replace deprecated
- org.openrewrite.node.migrate.http.replace-outgoing-message-headers
- Replace
OutgoingMessage._headersand._headerNameswith public methods - Replace deprecated
OutgoingMessage.prototype._headerswithgetHeaders(),setHeader(),removeHeader()andOutgoingMessage.prototype._headerNameswithgetHeaderNames()to address DEP0066 deprecation.
- Replace
- org.openrewrite.node.migrate.increase-node-engine-version
- Increase Node.js engine version
- Increases the upper bound of the
engines.nodeversion range in package.json to allow the specified Node.js version.
- org.openrewrite.node.migrate.increase-node-engine-version-in-github-actions
- Increase Node.js version in GitHub Actions
- Increases
node-versioninactions/setup-nodesteps in GitHub Actions workflows. Only modifies plain major version values (e.g.20) and x-ranges (e.g.20.x). Never decreases the version.
- org.openrewrite.node.migrate.net.remove-set-simultaneous-accepts
- Remove deprecated
net._setSimultaneousAccepts() - Remove calls to deprecated
net._setSimultaneousAccepts()which was an undocumented internal function that is no longer necessary.
- Remove deprecated
- org.openrewrite.node.migrate.process.coerce-process-exit-code
- Coerce
process.exit()andprocess.exitCodeto integer - Wraps non-integer values passed to
process.exit()or assigned toprocess.exitCodewithMath.trunc()to avoid the DEP0164 deprecation warning about implicit coercion to integer.
- Coerce
- org.openrewrite.node.migrate.process.remove-usage-of-features-tls-underscore_constants
- Remove usage of deprecated
process.features.tls_*properties - Remove references to deprecated
process.features.tls_*properties, replace withprocess.features.tls.
- Remove usage of deprecated
- org.openrewrite.node.migrate.stream.replace-internal-modules
- Replace deprecated
node:_stream_*withnode:stream - Replace deprecated internal stream module imports like
require('node:_stream_readable')with the publicnode:streammodule.
- Replace deprecated
- org.openrewrite.node.migrate.timers.find-timers-active
- Find deprecated
timers.active()andtimers._unrefActive()usage timers.active()(DEP0126) andtimers._unrefActive()(DEP0127) were deprecated and removed in Node.js 24. Usetimeout.refresh()instead.
- Find deprecated
- org.openrewrite.node.migrate.tls.find-tls-secure-pair
- Find deprecated
tls.SecurePairandtls.createSecurePair()usage tls.SecurePair(DEP0043) andtls.createSecurePair()(DEP0064) were deprecated and removed in Node.js 24. Usetls.TLSSocketinstead.
- Find deprecated
- org.openrewrite.node.migrate.tls.replace-internal-modules
- Replace deprecated
node:_tls_commonandnode:_tls_wrapwithnode:tls - Replace deprecated internal TLS module imports
require('node:_tls_common')andrequire('node:_tls_wrap')with the publicnode:tlsmodule.
- Replace deprecated
- org.openrewrite.node.migrate.upgrade-node-22
- Upgrade to Node.js 22
- Migrate deprecated APIs for Node.js 22 compatibility. Addresses Node 22 runtime deprecations and deprecations from earlier versions.
- org.openrewrite.node.migrate.upgrade-node-24
- Upgrade to Node.js 24
- Migrate deprecated APIs for Node.js 24 compatibility. Includes all migrations from Node.js 22, plus Node 23 and Node 24 deprecations.
- org.openrewrite.node.migrate.util.remove-promisify-on-promise
- Remove unnecessary
util.promisify()on Promise-returning functions - Removes
util.promisify()calls on functions that already return a Promise. Since Node.js v17.0.0, calling promisify on a function that returns a Promise emits a runtime deprecation warning (DEP0174).
- Remove unnecessary
- org.openrewrite.node.migrate.util.replace-is-webassembly-compiled-module
- Replace deprecated
util.types.isWebAssemblyCompiledModule() - Replace
util.types.isWebAssemblyCompiledModule(value)withvalue instanceof WebAssembly.Module.
- Replace deprecated
- org.openrewrite.node.migrate.util.replace-util-extend
- Replace deprecated
util._extend()withObject.assign() - Replace deprecated
util._extend(target, source)calls withObject.assign(target, source)which preserves the mutation behavior.
- Replace deprecated
- org.openrewrite.node.migrate.util.replace-util-log
- Replace deprecated
util.log()withconsole.log() - Replace deprecated
util.log()calls withconsole.log(). Note:util.log()included timestamps, butconsole.log()does not.
- Replace deprecated
- org.openrewrite.node.migrate.util.use-native-type-checking-methods
- Replace deprecated
util.isX()methods with native JavaScript - The
utilmodule's type-checking methods have been removed in Node 22.
- Replace deprecated
- org.openrewrite.node.migrate.zlib.replace-bytes-read
- Replace deprecated
zlib.bytesReadwithzlib.bytesWritten - Replace deprecated
bytesReadproperty on zlib streams withbytesWritten.
- Replace deprecated
- org.openrewrite.node.security.remove-redundant-overrides
- Remove redundant dependency overrides
- Removes overrides/resolutions from package.json that are redundant because the dependency tree already resolves to the overridden version or higher.
- org.openrewrite.nodejs.DependencyVulnerabilityCheck
- Find and fix vulnerable npm dependencies
- This software composition analysis (SCA) tool detects and upgrades dependencies with publicly disclosed vulnerabilities. This recipe both generates a report of vulnerable dependencies and upgrades to newer versions with fixes. This recipe only upgrades to the latest patch version. If a minor or major upgrade is required to reach the fixed version, this recipe will not make any changes. Vulnerability information comes from the GitHub Security Advisory Database, which aggregates vulnerability data from several public databases, including the National Vulnerability Database maintained by the United States government. Dependencies following Semantic Versioning will see their patch version updated where applicable.
- org.openrewrite.nodejs.UpgradeDependencyVersion
- Upgrade Node.js dependencies
- Upgrade matching Node.js direct dependencies.
- org.openrewrite.nodejs.search.DatabaseInteractionInsights
- Javascript database interaction library insights
- Discover which popular javascript database interaction libraries (Sequelize, TypeORM, Mongoose, etc.) are being used in your projects.
- org.openrewrite.nodejs.search.DependencyInsight
- Node.js dependency insight
- Identify the direct and transitive Node.js dependencies used in a project.
- org.openrewrite.nodejs.search.FindNodeProjects
- Find Node.js projects
- Find Node.js projects and summarize data about them.
- org.openrewrite.nodejs.search.FormHandlingInsights
- Javascript form handling library insights
- Discover which popular javascript form handling libraries (Formik, React Hook Form, Yup, etc.) are being used in your projects.
- org.openrewrite.nodejs.search.LintingFormattingInsights
- Javascript linting & formatting library insights
- Discover which popular javascript linting and formatting libraries (ESLint, Prettier, Stylelint, etc.) are being used in your projects.
- org.openrewrite.nodejs.search.RealTimeCommunicationInsights
- Javascript real-time communication library insights
- Discover which popular javascript real-time communication libraries (Socket.io, Ws, SockJS, etc.) are being used in your projects.
- org.openrewrite.nodejs.search.SecurityInsights
- Javascript security library insights
- Discover which popular javascript security libraries (Helmet, Cors, Bcrypt, etc.) are being used in your projects.
- org.openrewrite.nodejs.search.ServerSideFrameworksInsights
- Javascript server-side frameworks insights
- Discover which popular javascript server-side frameworks (Express, Koa, Hapi, etc.) are being used in your projects.
- org.openrewrite.nodejs.search.StateManagementInsights
- Javascript state management library insights
- Discover which popular javascript state management libraries (Redux, MobX, Vuex, etc.) are being used in your projects.
- org.openrewrite.nodejs.search.TaskRunnersBuildToolsInsights
- Javascript task runners & build tools insights
- Discover which popular javascript task runners and build tools (Webpack, Parcel, Gulp, etc.) are being used in your projects.
- org.openrewrite.nodejs.search.TestingInsights
- Javascript testing library insights
- Discover which popular javascript testing libraries (Jest, Mocha, Chai, etc.) are being used in your projects.
- org.openrewrite.nodejs.search.UIInsights
- Javascript UI library insights
- Discover which popular javascript UI libraries (React, Vue.js, Angular, etc.) are being used in your projects.
- org.openrewrite.nodejs.search.UtilityInsights
- Javascript utility library insights
- Discover which popular javascript utility libraries (Lodash, Moment.js, Date-fns, etc.) are being used in your projects.
- org.openrewrite.recipe.rewrite-nodejs.InlineDeprecatedMethods
- Inline deprecated delegating methods
- Automatically generated recipes to inline deprecated method calls that delegate to other methods in the same class.
rewrite-reactive-streams
- org.openrewrite.reactive.reactor.ReactorBestPractices
- Reactor Best Practices
- This recipe applies best practices for using Reactor.
- org.openrewrite.reactive.reactor.ReactorDoAfterSuccessOrErrorToTap
- Replace
doAfterSuccessOrErrorcalls withtapoperator - As of reactor-core 3.5 the
doAfterSuccessOrErrormethod is removed, this recipe replaces it with thetapoperator.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCacheToSinkRecipes
- Replace various
Processor.cachecalls with theirSinksequivalent - As of 3.5 Processors are deprecated and Sinks are preferred.
- Replace various
- org.openrewrite.reactive.reactor.ReactorProcessorCacheToSinkRecipes$ReplayProcessorCacheDefaultToSinkRecipe
- Replace
ReplayProcessor.cacheLast()withSinks.many().replay().latest() - As of 3.5 ReplayProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCacheToSinkRecipes$ReplayProcessorCacheToSinkRecipe
- Replace
ReplayProcessor.cacheLast()withSinks.many().replay().latest() - As of 3.5 ReplayProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes
- Replace various
Processor.createcalls with theirSinksequivalent - As of 3.5 Processors are deprecated and Sinks are preferred.
- Replace various
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$DirectProcessorCreateToSinkRecipe
- Replace
DirectProcessor.create()withSinks.many().multicast().directBestEffort() - As of 3.5 DirectProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$EmitterProcessorCreateBooleanToSinkRecipe
- Replace
EmitterProcessor.create(Boolean)withSinks.many().multicast().onBackpressureBuffer(Queues.SMALL_BUFFER_SIZE, Boolean) - As of 3.5 EmitterProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$EmitterProcessorCreateIntBooleanToSinkRecipe
- Replace
EmitterProcessor.create(int, Boolean)withSinks.many().multicast().onBackpressureBuffer(int, Boolean) - As of 3.5 EmitterProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$EmitterProcessorCreateIntToSinkRecipe
- Replace
EmitterProcessor.create(int)withSinks.many().multicast().onBackpressureBuffer(int) - As of 3.5 EmitterProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$EmitterProcessorCreateToSinkRecipe
- Replace
EmitterProcessor.create()withSinks.many().multicast().onBackpressureBuffer() - As of 3.5 EmitterProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$MonoProcessorCreateToSinkRecipe
- Replace
MonoProcessor.create()withSinks.one() - As of 3.5 MonoProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$ReplayProcessorCreateIntLiteralFalseToSinkRecipe
- Replace
ReplayProcessor.create(int, false)withSinks.many().replay().limit(int) - As of 3.5 ReplayProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$ReplayProcessorCreateIntLiteralTrueToSinkRecipe
- Replace
ReplayProcessor.create(int, true)withSinks.many().replay().all(int) - As of 3.5 ReplayProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$ReplayProcessorCreateIntToSinkRecipe
- Replace
ReplayProcessor.create(int)withSinks.many().replay().limit(int) - As of 3.5 ReplayProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$ReplayProcessorCreateSizeAndTimeoutSchedulerToSinkRecipe
- Replace
ReplayProcessor.createSizeAndTimeout(int, Duration, Scheduler)withSinks.many().replay().limit(int, Duration, Scheduler) - As of 3.5 ReplayProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$ReplayProcessorCreateSizeAndTimeoutToSinkRecipe
- Replace
ReplayProcessor.createSizeAndTimeout(int, Duration)withSinks.many().replay().limit(int, duration) - As of 3.5 ReplayProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$ReplayProcessorCreateTimeoutSchedulerToSinkRecipe
- Replace
ReplayProcessor.createTimeout(Duration, Scheduler)withSinks.many().replay().limit(Duration, Scheduler) - As of 3.5 ReplayProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$ReplayProcessorCreateTimeoutToSinkRecipe
- Replace
ReplayProcessor.createTimeout(Duration)withSinks.many().replay().limit(duration) - As of 3.5 ReplayProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$ReplayProcessorCreateToSinkRecipe
- Replace
ReplayProcessor.create()withSinks.many().replay().all() - As of 3.5 ReplayProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$UnicastProcessorCreateQueueConsumerDisposableToSinkRecipe
- Replace
UnicastProcessor.create(Queue, Consumer, Disposable)withSinks.many().unicast().onBackpressureBuffer(Queue, Disposable) - As of 3.5 UnicastProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$UnicastProcessorCreateQueueDisposableToSinkRecipe
- Replace
UnicastProcessor.create(Queue, Disposable)withSinks.many().unicast().onBackpressureBuffer(Queue, Disposable) - As of 3.5 UnicastProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$UnicastProcessorCreateQueueToSinkRecipe
- Replace
UnicastProcessor.create(Queue)withSinks.many().unicast().onBackpressureBuffer(Queue) - As of 3.5 UnicastProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.ReactorProcessorCreateToSinkRecipes$UnicastProcessorCreateToSinkRecipe
- Replace
UnicastProcessor.create()withSinks.many().unicast().onBackpressureBuffer() - As of 3.5 UnicastProcessor is deprecated and Sinks are preferred.
- Replace
- org.openrewrite.reactive.reactor.UpgradeReactor_3_5
- Migrate to Reactor 3.5
- Adopt to breaking changes in Reactor 3.5.
rewrite-sql
- org.openrewrite.sql.ChangeFunctionName
- Change a SQL function name
- When migrating between dialects, often one name can be substituted for another. For example, Oracle's
NVLfunction can be replaced with PostgresCOALESCE.
- org.openrewrite.sql.ConvertDataType
- Convert SQL data type
- When migrating between SQL dialects, data types often need to be converted. For example, Oracle's
VARCHAR2can be replaced with PostgresVARCHAR, orNUMBERwithNUMERIC.
- org.openrewrite.sql.ConvertOracleDataTypesToPostgres
- Convert Oracle data types to PostgreSQL
- Replaces Oracle-specific data types with PostgreSQL equivalents.
- org.openrewrite.sql.ConvertOracleFunctionsToPostgres
- Convert Oracle functions to PostgreSQL
- Replaces Oracle-specific functions with PostgreSQL equivalents.
- org.openrewrite.sql.ConvertSqlServerDataTypesToPostgres
- Convert SQL Server data types to PostgreSQL
- Replaces SQL Server-specific data types with PostgreSQL equivalents.
- org.openrewrite.sql.ConvertSqlServerFunctionsToPostgres
- Convert SQL Server functions to PostgreSQL
- Replaces SQL Server-specific functions with PostgreSQL equivalents.
- org.openrewrite.sql.FindSql
- Find SQL in code and resource files
- Find SQL in code (e.g. in string literals) and in resources like those ending with
.sql.
- org.openrewrite.sql.FormatSql
- Format SQL in string text blocks
- Checks whether a text block may contain SQL, and if so, formats the text accordingly.
- org.openrewrite.sql.MigrateOracleToPostgres
- Migrate Oracle SQL to PostgreSQL
- Converts Oracle-specific SQL syntax and functions to PostgreSQL equivalents.
- org.openrewrite.sql.MigrateSqlServerToPostgres
- Migrate SQL Server to PostgreSQL
- Converts Microsoft SQL Server-specific SQL syntax and functions to PostgreSQL equivalents.
- org.openrewrite.sql.search.FindFunction
- Find SQL function
- Find SQL functions by name.
rewrite-static-analysis-python
- org.openrewrite.python.cleanup.AssignIfExp
- Use inline conditional for simple
if/elseassignment - When an
if/elsepair each assign a single value to the same variable, rewrite as a ternary expression.
- Use inline conditional for simple
- org.openrewrite.python.cleanup.AugAssign
- Shorten assignment to compound operator form
- Convert
target = target op valueintotarget op= valuefor arithmetic operators (+, -, *, /, %).
- org.openrewrite.python.cleanup.BinOpIdentity
- Collapse self-cancelling
^/-with duplicate operands to0 - When both operands of
^or-are the same expression, reduce to0(the self-cancelling identity).
- Collapse self-cancelling
- org.openrewrite.python.cleanup.BooleanIfExpIdentity
- Collapse boolean ternary to bare condition
- Replace
True if expr else FalsewithexprandFalse if expr else Truewithnot expr, removing the redundant ternary wrapper.
- org.openrewrite.python.cleanup.BreakOrContinueOutsideLoop
- Remove
break/continueoutside loop - Remove
breakandcontinuestatements that are not inside any for or while loop.
- Remove
- org.openrewrite.python.cleanup.ChainCompares
- Use chained comparison syntax
- Merge two relational tests that share a middle operand into a single chained comparison, e.g.
0 < idx and idx < sizebecomes0 < idx < size.
- org.openrewrite.python.cleanup.ClassMethodFirstArgName
- Standardize
@classmethodfirst parameter tocls - Ensure that
@classmethodmethods useclsas their first parameter, as required by PEP 8, and update all body references.
- Standardize
- org.openrewrite.python.cleanup.CollectionBuiltinToComprehension
- Use comprehension syntax instead of
list()/set()around generators - Wrapping a generator in
list()orset()is less idiomatic than the equivalent bracket/brace comprehension syntax.
- Use comprehension syntax instead of
- org.openrewrite.python.cleanup.CollectionIntoSet
- Prefer set literals in
inmembership tests - When a list or tuple of literals appears on the right side of an
intest, convert it to a set literal for constant-time lookup.
- Prefer set literals in
- org.openrewrite.python.cleanup.CollectionToBool
- Substitute constant collection condition with boolean
- When a list, tuple, dict, or set literal is used as an
iforwhilecondition, replace it withTrue(non-empty) orFalse(empty) to state the intent directly.
- org.openrewrite.python.cleanup.ComprehensionToGenerator
- Use generator expression instead of list comprehension in iterable-accepting calls
- Functions that consume iterables lazily (e.g.
any,sum,sorted) do not need a list comprehension -- a generator expression suffices.
- org.openrewrite.python.cleanup.ConvertAnyToIn
- Rewrite
any(v == literal ...)asliteral in collection - An
any()generator that tests equality against a literal value is equivalent to theinmembership operator, which is clearer.
- Rewrite
- org.openrewrite.python.cleanup.DataframeAppendToConcat
- Migrate deprecated
.append()topd.concat() DataFrame.append()no longer exists in pandas 2.0+. This recipe rewrites.append(x)calls topd.concat([df, x]).
- Migrate deprecated
- org.openrewrite.python.cleanup.DeMorgan
- Flatten negated logic via De Morgan's identities
- Use De Morgan's identities to remove double negation and to distribute
notinto compound conditions, e.g.not not finishedbecomesfinishedandnot (m and n)becomesnot m or not n.
- org.openrewrite.python.cleanup.DefaultMutableArg
- Guard mutable default arguments with
Nonesentinel - Change mutable default values (
[],\{\},set()) toNoneand prepend anif arg is None: arg = <original>guard so each call gets its own fresh instance.
- Guard mutable default arguments with
- org.openrewrite.python.cleanup.DictLiteral
- Use
\{\}literal instead ofdict()constructor - Convert no-argument
dict()calls to the\{\}literal, which is more concise and avoids a function call.
- Use
- org.openrewrite.python.cleanup.DoNotUseBareExcept
- Narrow bare
except:toexcept Exception: - An unqualified
except:intercepts every exception, includingSystemExitandKeyboardInterrupt. SpecifyingExceptionrestricts the handler to ordinary runtime errors.
- Narrow bare
- org.openrewrite.python.cleanup.EqualityIdentity
- Fold same-literal
==/!=comparisons to boolean constants - When both sides of
==or!=are the same literal, replace the expression withTrueorFalserespectively.
- Fold same-literal
- org.openrewrite.python.cleanup.FlipComparison
- Reorder comparisons to put literals on the right
- Swap operands when a constant appears on the left of a comparison, e.g.
42 == countbecomescount == 42, mirroring the relational operator as needed.
- org.openrewrite.python.cleanup.IdentityComprehension
- Simplify identity comprehension to
list()/set()call - A comprehension that simply passes through each element unchanged is equivalent to calling
list()orset()on the iterable.
- Simplify identity comprehension to
- org.openrewrite.python.cleanup.InstanceMethodFirstArgName
- Standardize instance method first parameter to
self - Ensure instance methods use
selfas their first parameter per PEP 8 and rename all body references. Methods decorated with@staticmethodor@classmethodare not affected.
- Standardize instance method first parameter to
- org.openrewrite.python.cleanup.InvertAnyAll
- Swap
not all()/not any()by negating the comparison - Apply De Morgan's law to replace
not all(cond ...)withany(negated_cond ...)ornot any(cond ...)withall(negated_cond ...).
- Swap
- org.openrewrite.python.cleanup.InvertAnyAllBody
- Apply De Morgan's law to
any(not ...)/all(not ...) - When the generator body just negates the loop variable, De Morgan's law lets us eliminate the generator entirely:
any(not v for v in seq)becomesnot all(seq), and the reverse.
- Apply De Morgan's law to
- org.openrewrite.python.cleanup.ListLiteral
- Use
[]literal instead oflist()constructor - Convert no-argument
list()calls to the[]literal, which is more concise and avoids a function call.
- Use
- org.openrewrite.python.cleanup.MergeComparisons
- Consolidate repeated
==withorintoin - Fold
var == a or var == bintovar in [a, b], reducing duplication and improving readability.
- Consolidate repeated
- org.openrewrite.python.cleanup.MergeElseIfIntoElif
- Convert
else: iftoelif - When an
elseclause contains nothing but anif, rewrite it aselifto eliminate extra nesting.
- Convert
- org.openrewrite.python.cleanup.MergeIsinstance
- Merge
isinstance()calls - Merge
isinstance(x, A) or isinstance(x, B)intoisinstance(x, (A, B))for cleaner type checking.
- Merge
- org.openrewrite.python.cleanup.MergeNestedIfs
- Collapse nested
ifinto a singleandcondition - When two
ifstatements are nested with noelseon either, join their conditions withandand flatten the body.
- Collapse nested
- org.openrewrite.python.cleanup.NoneCompare
- Compare to
Nonewith identity operators (is/is not) - Switch
== Nonetois Noneand!= Nonetois not None, following PEP 8 singleton comparison guidance.
- Compare to
- org.openrewrite.python.cleanup.OrIfExpIdentity
- Replace self-referencing ternary with
or - When a ternary's condition and true-branch name the same variable, rewrite
val if val else fallbackasval or fallbackto avoid repeating the name.
- Replace self-referencing ternary with
- org.openrewrite.python.cleanup.PandasAvoidInplace
- Eliminate
inplace=Truein favor of reassignment - Convert pandas operations that use
inplace=Trueinto reassignment form, e.g.df.drop_duplicates(inplace=True)becomesdf = df.drop_duplicates().
- Eliminate
- org.openrewrite.python.cleanup.PythonBestPractices
- Python cleanup suite
- Run every Python cleanup recipe in one pass -- literal simplification, boolean and comparison tidying, dead code removal, naming fixes, pandas modernization, and more.
- org.openrewrite.python.cleanup.RaiseFromPreviousError
- Chain exceptions with
raise ... fromin except blocks - Raise statements inside except blocks should use
fromto chain the new exception to the caught one, preserving the full traceback.
- Chain exceptions with
- org.openrewrite.python.cleanup.RemoveAssertTrue
- Delete no-op
assert Truestatements - Delete bare
assert Truestatements, which are always satisfied and have no effect. Assertions that carry a message string are preserved.
- Delete no-op
- org.openrewrite.python.cleanup.RemoveDictKeys
- Drop redundant
.keys()on dict iteration - Dictionaries iterate over their keys by default, making explicit
.keys()calls unnecessary in for-loops andinexpressions.
- Drop redundant
- org.openrewrite.python.cleanup.RemoveDuplicateDictKey
- Deduplicate repeated keys in dict literals
- When a dict literal contains the same key more than once, only the final value survives at runtime. This removes the shadowed entries.
- org.openrewrite.python.cleanup.RemoveDuplicateSetKey
- Deduplicate repeated elements in set literals
- Set literals with repeated values have redundant entries that are discarded at runtime. This removes the duplicates, keeping the last one.
- org.openrewrite.python.cleanup.RemoveEmptyNestedBlock
- Delete
ifblocks whose body is onlypass - Delete
ifstatements that contain nothing butpassand have noelsebranch.for/whileloops are left alone because iterating may have side effects.
- Delete
- org.openrewrite.python.cleanup.RemoveNoneFromDefaultGet
- Remove redundant
Nonedefault fromdict.get() - Remove redundant
Nonedefault argument fromdict.get()calls sinceNoneis already the default return value.
- Remove redundant
- org.openrewrite.python.cleanup.RemovePassBody
- Drop
pass-onlyifbody by inverting the guard - When an
ifbody contains onlypassand is followed by anelse, flip the condition and use the else body directly.
- Drop
- org.openrewrite.python.cleanup.RemovePassElif
- Drop
pass-onlyelifby negating its condition - When an
elifbody is onlypassand anelsefollows, invert theelifcondition and absorb the else body.
- Drop
- org.openrewrite.python.cleanup.RemoveRedundantBoolean
- Eliminate boolean literal from
and/or - Strip
TrueorFalsefromand/orexpressions where the literal has no effect on the result, e.g.True and valreduces tovalandFalse and valreduces toFalse.
- Eliminate boolean literal from
- org.openrewrite.python.cleanup.RemoveRedundantCondition
- Remove redundant ternary condition
- When both branches of a ternary expression are identical, simplify
y if z else ytoy.
- org.openrewrite.python.cleanup.RemoveRedundantConstructorInDictUnion
- Unwrap unnecessary
dict()from union operands - The
|operator already produces a fresh dict, so wrapping an operand indict()is redundant and can be removed.
- Unwrap unnecessary
- org.openrewrite.python.cleanup.RemoveRedundantContinue
- Strip trailing
continuefrom loop body - Strip
continuewhen it is the final statement in a loop body, since the loop naturally advances to the next iteration.
- Strip trailing
- org.openrewrite.python.cleanup.RemoveRedundantFstring
- Drop
fprefix from strings without placeholders - When an f-string has no
\{...\}expressions, strip thefprefix and convert it to an ordinary string literal.
- Drop
- org.openrewrite.python.cleanup.RemoveRedundantIf
- Simplify negated
eliftoelse - When an
elifcondition is the exact negation of the precedingif, replace it withelsesince the test is redundant.
- Simplify negated
- org.openrewrite.python.cleanup.RemoveRedundantPass
- Delete unnecessary
passin non-empty blocks - Delete
passwhen the enclosing block already contains other statements;passis only useful as a placeholder in empty blocks.
- Delete unnecessary
- org.openrewrite.python.cleanup.RemoveRedundantPathExists
- Drop
exists()check beforeis_dir()/is_file() - Drop
path.exists()when it isand-ed withis_dir()oris_file(), which inherently returnFalsefor missing paths.
- Drop
- org.openrewrite.python.cleanup.RemoveRedundantSliceIndex
- Drop default-value slice boundaries
- Omit slice start/stop when they equal
0andlen(seq)respectively, e.g.data[0:len(data)]becomesdata[:].
- org.openrewrite.python.cleanup.RemoveStrFromFstring
- Strip
str()from f-string placeholders - F-string placeholders convert values to strings automatically, so wrapping expressions in
str()inside\{...\}is redundant.
- Strip
- org.openrewrite.python.cleanup.RemoveStrFromPrint
- Unwrap
str()fromprint()arguments print()automatically converts its arguments to strings, so an explicitstr()wrapper is unnecessary and can be removed.
- Unwrap
- org.openrewrite.python.cleanup.RemoveUnitStepFromRange
- Drop unnecessary step
1argument fromrange() - Shorten
range(a, b, 1)torange(a, b)becauserangealready defaults to a step of one.
- Drop unnecessary step
- org.openrewrite.python.cleanup.RemoveUnnecessaryElse
- Drop
elseafter early-exitifbranch - When the
ifbody always exits via return, raise, continue, or break, remove theelseand dedent its contents.
- Drop
- org.openrewrite.python.cleanup.RemoveUnreachableCode
- Strip dead code after terminal statements
- Delete statements that follow a
return,raise,continue, orbreakin the same block, since they can never execute.
- org.openrewrite.python.cleanup.RemoveZeroFromRange
- Drop unnecessary
0start argument fromrange() - Shorten
range(0, n)torange(n)becauserangealready defaults to starting at zero.
- Drop unnecessary
- org.openrewrite.python.cleanup.ReplaceApplyWithMethodCall
- Convert
apply('name')to a direct method invocation - When
apply()receives a string literal like'sum'or'mean', rewrite the call as a direct method invocation on the object.
- Convert
- org.openrewrite.python.cleanup.ReturnOrYieldOutsideFunction
- Remove
return/yieldoutside function - Remove
returnandyieldstatements that are not inside any function or method definition.
- Remove
- org.openrewrite.python.cleanup.SimplifyBooleanComparison
- Remove explicit True/False comparisons
- Drop unnecessary
== True,!= False, and similar tests against boolean literals, leaving just the expression ornot expr.
- org.openrewrite.python.cleanup.SimplifyConstantSum
- Simplify
sum(1 for x in items if cond)tosum(bool(cond) for x in items) - Replace
sum(1 for x in items if cond)withsum(bool(cond) for x in items)by moving the filter condition into abool()wrapper.
- Simplify
- org.openrewrite.python.cleanup.SimplifyDictionaryUpdate
- Convert one-item
dict.update()to bracket assignment - When
.update()receives a dictionary literal containing exactly one key, rewrite it as a direct key assignment for clarity and efficiency.
- Convert one-item
- org.openrewrite.python.cleanup.SimplifyDivision
- Convert
int(a / b)to floor division - Replace
int(a / b)with Python's floor-division operatora // bfor a more concise expression.
- Convert
- org.openrewrite.python.cleanup.SimplifyEmptyCollectionComparison
- Use truthiness instead of empty-container equality
- Convert
== ""/== []/== \{\}/== ()intonot varand the corresponding!=forms intovar, relying on Python's truthiness semantics for empty collections.
- org.openrewrite.python.cleanup.SimplifyFstringFormatting
- Fold constants and flatten nested f-strings
- Inline constant values directly into f-string text and unwrap nested f-strings into their enclosing string.
- org.openrewrite.python.cleanup.SimplifyGenerator
- Pass iterable directly to
any()/all()instead of identity generator - An identity generator that yields every element unchanged is redundant inside
any()orall()-- pass the collection directly.
- Pass iterable directly to
- org.openrewrite.python.cleanup.SimplifyLenComparison
- Replace
len()emptiness check with truthiness - Rewrite
len(seq) > 0/len(seq) != 0toseqandlen(seq) == 0tonot seq, leveraging Python's built-in truthiness for collections.
- Replace
- org.openrewrite.python.cleanup.SimplifyNegativeIndex
- Use negative index instead of
len()offset - Rewrite
seq[len(seq) - k]asseq[-k], using Python's native negative-indexing support.
- Use negative index instead of
- org.openrewrite.python.cleanup.SimplifySingleExceptionTuple
- Unwrap one-element exception tuple in
except - A tuple containing only one exception type is needlessly verbose. This unwraps it to the plain
except ExcType:form.
- Unwrap one-element exception tuple in
- org.openrewrite.python.cleanup.SimplifyStrLenComparison
- Compare string to
""instead of checkinglen() - Replace
len(text) == 0withtext == ""andlen(text) > 0/len(text) != 0withtext != "", comparing the string directly rather than measuring its length.
- Compare string to
- org.openrewrite.python.cleanup.SimplifySubstringSearch
- Replace
.find()check within/not in - Rewrite
.find()return-value checks as membership tests:text.find(sub) == -1becomessub not in textandtext.find(sub) != -1becomessub in text.
- Replace
- org.openrewrite.python.cleanup.SquareIdentity
- Rewrite self-multiplication as
** 2 - When an expression is multiplied by itself, rewrite it using the exponentiation operator (
** 2) for clarity.
- Rewrite self-multiplication as
- org.openrewrite.python.cleanup.StrPrefixSuffix
- Prefer
startswith/endswithover slice comparison - Rewrite
s[:N] == "lit"ass.startswith("lit")ands[-N:] == "lit"ass.endswith("lit")when the slice length equals the literal length.
- Prefer
- org.openrewrite.python.cleanup.SwapIfElseBranches
- Flip empty
if-body by negating the condition - When the
ifbranch is justpassand anelseexists, invert the test and promote the else body to the if body.
- Flip empty
- org.openrewrite.python.cleanup.SwapIfExpression
- Swap ternary branches to drop negated condition
- Flip the branches of a conditional expression whose test uses
not, eliminating the negation for clearer intent.
- org.openrewrite.python.cleanup.SwapVariable
- Simplify temp-variable swap to tuple unpacking
- Detect the three-line swap idiom (
tmp = x; x = y; y = tmp) and condense it intox, y = y, xusing tuple unpacking.
- org.openrewrite.python.cleanup.TernaryToIfExpression
- Convert
and/orternary trick to conditional expression - Rewrite the legacy
cond and val or fallbackidiom asval if cond else fallbackto avoid silent bugs whenvalis falsy.
- Convert
- org.openrewrite.python.cleanup.TupleLiteral
- Use
()literal instead oftuple()constructor - Convert no-argument
tuple()calls to the()literal, which is more concise and avoids a function call.
- Use
- org.openrewrite.python.cleanup.UnwrapIterableConstruction
- Flatten redundant collection constructor wrapping a literal
- When
tuple(),list(), orset()wraps a single list or tuple literal, remove the constructor and use the target literal form directly.
- org.openrewrite.python.cleanup.UseContextlibSuppress
- Replace
try/except: passwithcontextlib.suppress() - When an except handler only contains
pass, the intent is to suppress the error.contextlib.suppress()states this explicitly and eliminates the try/except boilerplate.
- Replace
- org.openrewrite.python.cleanup.UseDatetimeNowNotToday
- Use
datetime.now()instead ofdatetime.today() - Replace
datetime.today()withdatetime.now(). Both are equivalent, butnow()is more explicit and supports timezone arguments.
- Use
- org.openrewrite.python.cleanup.UseDictionaryUnion
- Use dict union operator instead of double-star unpacking
- Dict literals made up entirely of
**unpacking can be rewritten with the|union operator available since Python 3.9.
- org.openrewrite.python.cleanup.UseFileIterator
- Iterate over file objects directly, not via
readlines() - File objects are iterable and yield lines on demand, so calling
.readlines()to build an intermediate list is unnecessary.
- Iterate over file objects directly, not via
- org.openrewrite.python.cleanup.UseGetitemForReMatchGroups
- Use bracket access for
re.Matchgroups - Replace
match.group(n)withmatch[n]to use the shorter subscript syntax available since Python 3.6.
- Use bracket access for
- org.openrewrite.python.cleanup.UseIsna
- Use
.isna()instead of== np.nancomparisons - Rewrite
== np.nanand== numpy.nanequality tests as.isna()calls, since direct NaN comparison always evaluates to False.
- Use
- org.openrewrite.python.cleanup.UseStringRemoveAffix
- Replace string slicing with
removeprefix/removesuffix - Replace
if text.startswith(s): text = text[N:]withtext = text.removeprefix(s)and the equivalentendswithpattern withremovesuffix(Python 3.9+).
- Replace string slicing with
- org.openrewrite.python.cleanup.UselessElseOnLoop
- Flatten
for/elsewhen the loop has nobreak - A
for/elsewhere the loop body never breaks is misleading -- theelseruns every time. This moves the else body after the loop.
- Flatten
- org.openrewrite.python.cleanup.YieldFrom
- Collapse for-yield loop into
yield from - A for-loop that does nothing but yield the loop variable can be expressed as
yield from, which is shorter and delegates directly.
- Collapse for-yield loop into
rewrite-struts
- org.openrewrite.java.struts.MigrateStrutsDtd
- Migrate DTD to a specific Struts version
- Update Struts DTD to reflect the specified version.
- org.openrewrite.java.struts.migrate2.MigrateActionClass
- Migrate Struts 1 Action to Struts 2 ActionSupport
- Migrates Struts 1.x Action classes to Struts 2.x ActionSupport, transforming the execute method signature and return statements.
- org.openrewrite.java.struts.migrate2.MigrateJspTaglib
- Migrate JSP taglib directives for Struts 2
- Update Struts 1 taglib directives to Struts 2 taglib.
- org.openrewrite.java.struts.migrate2.MigrateJspTags
- Migrate Struts 1 JSP tags to Struts 2
- Transforms Struts 1 JSP tags (
html:,bean:,logic:) to Struts 2 tags (s:).
- org.openrewrite.java.struts.migrate2.MigrateStruts2
- Migrate to Struts 2.x from Struts 1.x
- Comprehensive migration from Struts 1.x to Struts 2.x framework.
- org.openrewrite.java.struts.migrate2.MigrateStrutsConfig
- Migrate
struts-config.xmltostruts.xml - Transforms Struts 1.x
struts-config.xmlto Struts 2.xstruts.xmlformat.
- Migrate
- org.openrewrite.java.struts.migrate2.MigrateWebXml
- Migrate web.xml from Struts 1 to Struts 2
- Converts Struts 1 ActionServlet configuration to Struts 2 StrutsPrepareAndExecuteFilter.
- org.openrewrite.java.struts.migrate6.MigrateAwareInterfaces
- Migrate Struts 2.0 interceptors to action "aware" interfaces
- These types have moved to a new package in Struts 6.0 and their methods have been renamed from set* to with*.
- org.openrewrite.java.struts.migrate6.MigrateDateTagFormat
- Migrate Struts date tag format patterns
- Converts SimpleDateFormat patterns in
<s:date>tags to DateTimeFormatter-compatible patterns. Struts 6.0 uses DateTimeFormatter instead of SimpleDateFormat, which has different pattern letter meanings.
- org.openrewrite.java.struts.migrate6.MigrateDynamicMethodInvocation
- Migrate Dynamic Method Invocation to explicit action mappings
- Identifies Struts configurations using Dynamic Method Invocation (DMI) and marks them for migration, as DMI is disabled by default in Struts 6 for security reasons.
- org.openrewrite.java.struts.migrate6.MigrateOpenSymphonyClasses
- Migrate OpenSymphony classes to Struts 6.0
- Migrate classes from
com.opensymphony.xwork2to their replacements inorg.apache.struts2.
- org.openrewrite.java.struts.migrate6.MigrateStaticOgnlMethodAccess
- Migrate static OGNL method access to action wrapper methods
- Migrates OGNL expressions using static method access (e.g.,
@com.app.Util@makeCode()) to use action wrapper methods instead. Static method access is disabled by default in Struts 6 for security reasons.
- org.openrewrite.java.struts.migrate6.MigrateStruts6
- Migrate to Struts 6.0
- Migrate Struts 2.x to Struts 6.0.
- org.openrewrite.java.struts.migrate6.MigrateStruts6Constants
- Migrate to Struts 6.0 constants
- All Xwork constants had been already deprecated, with this version all of them have been removed and Struts constants have been used instead.
- org.openrewrite.java.struts.migrate6.MigrateValidatorDtd
- Migrate
xwork-validatorDTD to 1.0.4 - Update
xwork-validatorDTD from 1.0.3 to 1.0.4 for Struts 6 compatibility.
- Migrate
- org.openrewrite.java.struts.migrate6.RemoveFreemarkerHtmlBuiltin
- Remove deprecated Freemarker
?htmlbuilt-in - Removes the deprecated
?htmlbuilt-in from Freemarker templates. After migrating to Struts 6 with the latest Freemarker (which enables auto-escaping by default), the?htmlbuilt-in is no longer needed and should be removed. See the Struts 2.5 to 6.0 migration guide.
- Remove deprecated Freemarker
- org.openrewrite.java.struts.migrate6.UpgradeStruts6Dependencies
- Upgrade Struts 6.0 dependencies
- Upgrade Struts 2.x dependencies to Struts 6.0.
- org.openrewrite.java.struts.migrate7.MigrateStruts7
- Migrate to Struts 7.0
- Migrate Struts 6.x to Struts 7.x.
- org.openrewrite.java.struts.migrate7.RenameOpenSymphonyToStruts2
- Rename OpenSymphony / XWork classes to Struts 7 packages
- Updates classes moved from com.opensymphony.xwork2.* to their new org.apache.struts2.* packages in Struts 7.
- org.openrewrite.java.struts.migrate7.UpdateStruts7Constants
- Align Struts XML constants for Struts 7
- Updates Struts XML constants that were renamed or tightened in Struts 7.
- org.openrewrite.java.struts.search.FindStaticOgnlMethodAccess
- Find static OGNL method access
- Find OGNL expressions that use static method access (e.g.,
@com.app.Util@makeCode()), which is disabled by default in Struts 6 for security reasons. These expressions need to be migrated to use action instance methods instead.
- org.openrewrite.java.struts.search.FindStrutsActions
- Find Struts actions
- Find actions and their associated definitions.
rewrite-terraform
- org.openrewrite.terraform.AddConfiguration
- Add Terraform configuration
- If the configuration has a different value, leave it alone. If it is missing, add it.
- org.openrewrite.terraform.ChangeResourceAttribute
- Change Terraform resource attribute
- Change the value of a Terraform resource attribute if it matches a given pattern.
- org.openrewrite.terraform.MoveProviderVersionToRequiredProviders
- Move provider version to
required_providers - In Terraform 0.13+, version constraints should be specified in the
terraform \{ required_providers \{ ... \} \}block instead of theproviderblock. This recipe removes theversionattribute fromproviderblocks and adds it torequired_providers.
- Move provider version to
- org.openrewrite.terraform.SecureRandom
- Use a long enough byte length for
randomresources - Use a long enough byte length for
randomresources.
- Use a long enough byte length for
- org.openrewrite.terraform.UpgradeTerraformTo0_14
- Upgrade Terraform to 0.14
- Migrate Terraform configuration from 0.13 to 0.14. Moves version constraints from
providerblocks toterraform \{ required_providers \{ ... \} \}.
- org.openrewrite.terraform.aws.AWSBestPractices
- Best practices for AWS
- Securely operate on Amazon Web Services.
- org.openrewrite.terraform.aws.DisableInstanceMetadataServiceV1
- Disable Instance Metadata Service version 1
- As a request/response method IMDSv1 is prone to local misconfigurations.
- org.openrewrite.terraform.aws.EnableApiGatewayCaching
- Enable API gateway caching
- Enable caching for all methods of API Gateway.
- org.openrewrite.terraform.aws.EnableDynamoDbPITR
- Enable point-in-time recovery for DynamoDB
- DynamoDB Point-In-Time Recovery (PITR) is an automatic backup service for DynamoDB table data that helps protect your DynamoDB tables from accidental write or delete operations.
- org.openrewrite.terraform.aws.EnableECRScanOnPush
- Scan images pushed to ECR
- ECR Image Scanning assesses and identifies operating system vulnerabilities. Using automated image scans you can ensure container image vulnerabilities are found before getting pushed to production.
- org.openrewrite.terraform.aws.EncryptAuroraClusters
- Encrypt Aurora clusters
- Native Aurora encryption helps protect your cloud applications and fulfils compliance requirements for data-at-rest encryption.
- org.openrewrite.terraform.aws.EncryptCodeBuild
- Encrypt CodeBuild projects
- Build artifacts, such as a cache, logs, exported raw test report data files, and build results, are encrypted by default using CMKs for Amazon S3 that are managed by the AWS Key Management Service.
- org.openrewrite.terraform.aws.EncryptDAXStorage
- Encrypt DAX storage at rest
- DAX encryption at rest automatically integrates with AWS KMS for managing the single service default key used to encrypt clusters.
- org.openrewrite.terraform.aws.EncryptDocumentDB
- Encrypt DocumentDB storage
- The encryption feature available for Amazon DocumentDB clusters provides an additional layer of data protection by helping secure your data against unauthorized access to the underlying storage.
- org.openrewrite.terraform.aws.EncryptEBSSnapshots
- Encrypt EBS snapshots
- EBS snapshots should be encrypted, as they often include sensitive information, customer PII or CPNI.
- org.openrewrite.terraform.aws.EncryptEBSVolumeLaunchConfiguration
- Encrypt EBS volume launch configurations
- EBS volumes allow you to create encrypted launch configurations when creating EC2 instances and auto scaling. When the entire EBS volume is encrypted, data stored at rest on the volume, disk I/O, snapshots created from the volume, and data in-transit between EBS and EC2 are all encrypted.
- org.openrewrite.terraform.aws.EncryptEBSVolumes
- Encrypt EBS volumes
- Encrypting EBS volumes ensures that replicated copies of your images are secure even if they are accidentally exposed. AWS EBS encryption uses AWS KMS customer master keys (CMK) when creating encrypted volumes and snapshots. Storing EBS volumes in their encrypted state reduces the risk of data exposure or data loss.
- org.openrewrite.terraform.aws.EncryptEFSVolumesInECSTaskDefinitionsInTransit
- Encrypt EFS Volumes in ECS Task Definitions in transit
- Enable attached EFS definitions in ECS tasks to use encryption in transit.
- org.openrewrite.terraform.aws.EncryptElastiCacheRedisAtRest
- Encrypt ElastiCache Redis at rest
- ElastiCache for Redis offers default encryption at rest as a service.
- org.openrewrite.terraform.aws.EncryptElastiCacheRedisInTransit
- Encrypt ElastiCache Redis in transit
- ElastiCache for Redis offers optional encryption in transit. In-transit encryption provides an additional layer of data protection when transferring data over standard HTTPS protocol.
- org.openrewrite.terraform.aws.EncryptNeptuneStorage
- Encrypt Neptune storage
- Encryption of Neptune storage protects data and metadata against unauthorized access.
- org.openrewrite.terraform.aws.EncryptRDSClusters
- Encrypt RDS clusters
- Native RDS encryption helps protect your cloud applications and fulfils compliance requirements for data-at-rest encryption.
- org.openrewrite.terraform.aws.EncryptRedshift
- Encrypt Redshift storage at rest
- Redshift clusters should be securely encrypted at rest.
- org.openrewrite.terraform.aws.EnsureAWSCMKRotationIsEnabled
- Ensure AWS CMK rotation is enabled
- Ensure AWS CMK rotation is enabled.
- org.openrewrite.terraform.aws.EnsureAWSEFSWithEncryptionForDataAtRestIsEnabled
- Ensure AWS EFS with encryption for data at rest is enabled
- Ensure AWS EFS with encryption for data at rest is enabled.
- org.openrewrite.terraform.aws.EnsureAWSEKSClusterEndpointAccessIsPubliclyDisabled
- Ensure AWS EKS cluster endpoint access is publicly disabled
- Ensure AWS EKS cluster endpoint access is publicly disabled.
- org.openrewrite.terraform.aws.EnsureAWSElasticsearchDomainEncryptionForDataAtRestIsEnabled
- Ensure AWS Elasticsearch domain encryption for data at rest is enabled
- Ensure AWS Elasticsearch domain encryption for data at rest is enabled.
- org.openrewrite.terraform.aws.EnsureAWSElasticsearchDomainsHaveEnforceHTTPSEnabled
- Ensure AWS Elasticsearch domains have
EnforceHTTPSenabled - Ensure AWS Elasticsearch domains have
EnforceHTTPSenabled.
- Ensure AWS Elasticsearch domains have
- org.openrewrite.terraform.aws.EnsureAWSElasticsearchHasNodeToNodeEncryptionEnabled
- Ensure AWS Elasticsearch has node-to-node encryption enabled
- Ensure AWS Elasticsearch has node-to-node encryption enabled.
- org.openrewrite.terraform.aws.EnsureAWSIAMPasswordPolicyHasAMinimumOf14Characters
- Ensure AWS IAM password policy has a minimum of 14 characters
- Ensure AWS IAM password policy has a minimum of 14 characters.
- org.openrewrite.terraform.aws.EnsureAWSLambdaFunctionIsConfiguredForFunctionLevelConcurrentExecutionLimit
- Ensure AWS Lambda function is configured for function-level concurrent execution limit
- Ensure AWS Lambda function is configured for function-level concurrent execution limit.
- org.openrewrite.terraform.aws.EnsureAWSLambdaFunctionsHaveTracingEnabled
- Ensure AWS Lambda functions have tracing enabled
- Ensure AWS Lambda functions have tracing enabled.
- org.openrewrite.terraform.aws.EnsureAWSRDSDatabaseInstanceIsNotPubliclyAccessible
- Ensure AWS RDS database instance is not publicly accessible
- Ensure AWS RDS database instance is not publicly accessible.
- org.openrewrite.terraform.aws.EnsureAWSS3ObjectVersioningIsEnabled
- Ensure AWS S3 object versioning is enabled
- Ensure AWS S3 object versioning is enabled.
- org.openrewrite.terraform.aws.EnsureAmazonEKSControlPlaneLoggingEnabledForAllLogTypes
- Ensure Amazon EKS control plane logging enabled for all log types
- Ensure Amazon EKS control plane logging enabled for all log types.
- org.openrewrite.terraform.aws.EnsureCloudTrailLogFileValidationIsEnabled
- Ensure CloudTrail log file validation is enabled
- Ensure CloudTrail log file validation is enabled.
- org.openrewrite.terraform.aws.EnsureDataStoredInAnS3BucketIsSecurelyEncryptedAtRest
- Ensure data stored in an S3 bucket is securely encrypted at rest
- Ensure data stored in an S3 bucket is securely encrypted at rest.
- org.openrewrite.terraform.aws.EnsureDetailedMonitoringForEC2InstancesIsEnabled
- Ensure detailed monitoring for EC2 instances is enabled
- Ensure detailed monitoring for EC2 instances is enabled.
- org.openrewrite.terraform.aws.EnsureEC2IsEBSOptimized
- Ensure EC2 is EBS optimized
- Ensure EC2 is EBS optimized.
- org.openrewrite.terraform.aws.EnsureECRRepositoriesAreEncrypted
- Ensure ECR repositories are encrypted
- Ensure ECR repositories are encrypted.
- org.openrewrite.terraform.aws.EnsureEnhancedMonitoringForAmazonRDSInstancesIsEnabled
- Ensure enhanced monitoring for Amazon RDS instances is enabled
- Ensure enhanced monitoring for Amazon RDS instances is enabled.
- org.openrewrite.terraform.aws.EnsureIAMPasswordPolicyExpiresPasswordsWithin90DaysOrLess
- Ensure IAM password policy expires passwords within 90 days or less
- Ensure IAM password policy expires passwords within 90 days or less.
- org.openrewrite.terraform.aws.EnsureIAMPasswordPolicyPreventsPasswordReuse
- Ensure IAM password policy prevents password reuse
- Ensure IAM password policy prevents password reuse.
- org.openrewrite.terraform.aws.EnsureIAMPasswordPolicyRequiresAtLeastOneLowercaseLetter
- Ensure IAM password policy requires at least one lowercase letter
- Ensure IAM password policy requires at least one lowercase letter.
- org.openrewrite.terraform.aws.EnsureIAMPasswordPolicyRequiresAtLeastOneNumber
- Ensure IAM password policy requires at least one number
- Ensure IAM password policy requires at least one number.
- org.openrewrite.terraform.aws.EnsureIAMPasswordPolicyRequiresAtLeastOneSymbol
- Ensure IAM password policy requires at least one symbol
- Ensure IAM password policy requires at least one symbol.
- org.openrewrite.terraform.aws.EnsureIAMPasswordPolicyRequiresAtLeastOneUppercaseLetter
- Ensure IAM password policy requires at least one uppercase letter
- Ensure IAM password policy requires at least one uppercase letter.
- org.openrewrite.terraform.aws.EnsureKinesisStreamIsSecurelyEncrypted
- Ensure Kinesis Stream is securely encrypted
- Ensure Kinesis Stream is securely encrypted.
- org.openrewrite.terraform.aws.EnsureRDSDatabaseHasIAMAuthenticationEnabled
- Ensure RDS database has IAM authentication enabled
- Ensure RDS database has IAM authentication enabled.
- org.openrewrite.terraform.aws.EnsureRDSInstancesHaveMultiAZEnabled
- Ensure RDS instances have Multi-AZ enabled
- Ensure RDS instances have Multi-AZ enabled.
- org.openrewrite.terraform.aws.EnsureRespectiveLogsOfAmazonRDSAreEnabled
- Ensure respective logs of Amazon RDS are enabled
- Ensure respective logs of Amazon RDS are enabled.
- org.openrewrite.terraform.aws.EnsureTheS3BucketHasAccessLoggingEnabled
- Ensure the S3 bucket has access logging enabled
- Ensure the S3 bucket has access logging enabled.
- org.openrewrite.terraform.aws.EnsureVPCSubnetsDoNotAssignPublicIPByDefault
- Ensure VPC subnets do not assign public IP by default
- Ensure VPC subnets do not assign public IP by default.
- org.openrewrite.terraform.aws.ImmutableECRTags
- Make ECR tags immutable
- Amazon ECR supports immutable tags, preventing image tags from being overwritten. In the past, ECR tags could have been overwritten, this could be overcome by requiring users to uniquely identify an image using a naming convention.
- org.openrewrite.terraform.aws.UpgradeAwsAuroraMySqlToV3
- Upgrade AWS Aurora MySQL to version 3 (MySQL 8.0)
- Upgrade
engine_versionto Aurora MySQL version 3 (MySQL 8.0 compatible) onaws_rds_clusterresources and setallow_major_version_upgrade = trueto permit the major version change.
- org.openrewrite.terraform.aws.UpgradeAwsAuroraPostgresToV17
- Upgrade AWS Aurora PostgreSQL to 17
- Upgrade
engine_versionto Aurora PostgreSQL 17 onaws_rds_clusterresources and setallow_major_version_upgrade = trueto permit the major version change.
- org.openrewrite.terraform.aws.UpgradeAwsRdsMySqlToV8_4
- Upgrade AWS RDS MySQL to 8.4
- Upgrade
engine_versionto MySQL 8.4 onaws_db_instanceresources and setallow_major_version_upgrade = trueto permit the major version change.
- org.openrewrite.terraform.aws.UpgradeAwsRdsPostgresToV17
- Upgrade AWS RDS PostgreSQL to 17
- Upgrade
engine_versionto PostgreSQL 17 onaws_db_instanceresources and setallow_major_version_upgrade = trueto permit the major version change.
- org.openrewrite.terraform.aws.UseHttpsForCloudfrontDistribution
- Use HTTPS for Cloudfront distribution
- Secure communication by default.
- org.openrewrite.terraform.azure.AzureBestPractices
- Best practices for Azure
- Securely operate on Microsoft Azure.
- org.openrewrite.terraform.azure.DisableKubernetesDashboard
- Disable Kubernetes dashboard
- Disabling the dashboard eliminates it as an attack vector. The dashboard add-on is disabled by default for all new clusters created on Kubernetes 1.18 or greater.
- org.openrewrite.terraform.azure.EnableAzureStorageAccountTrustedMicrosoftServicesAccess
- Enable Azure Storage Account Trusted Microsoft Services access
- Certain Microsoft services that interact with storage accounts operate from networks that cannot be granted access through network rules. Using this configuration, you can allow the set of trusted Microsoft services to bypass those network rules.
- org.openrewrite.terraform.azure.EnableAzureStorageSecureTransferRequired
- Enable Azure Storage secure transfer required
- Microsoft recommends requiring secure transfer for all storage accounts.
- org.openrewrite.terraform.azure.EnableGeoRedundantBackupsOnPostgreSQLServer
- Enable geo-redundant backups on PostgreSQL server
- Ensure PostgreSQL server enables geo-redundant backups.
- org.openrewrite.terraform.azure.EncryptAzureVMDataDiskWithADECMK
- Encrypt Azure VM data disk with ADE/CMK
- Ensure Azure VM data disk is encrypted with ADE/CMK.
- org.openrewrite.terraform.azure.EnsureAKSPoliciesAddOn
- Ensure AKS policies add-on
- Azure Policy Add-on for Kubernetes service (AKS) extends Gatekeeper v3, an admission controller webhook for Open Policy Agent (OPA), to apply at-scale enforcements and safeguards on your clusters in a centralized, consistent manner.
- org.openrewrite.terraform.azure.EnsureAKVSecretsHaveAnExpirationDateSet
- Ensure AKV secrets have an expiration date set
- Ensure AKV secrets have an expiration date set.
- org.openrewrite.terraform.azure.EnsureASecurityContactPhoneNumberIsPresent
- Ensure a security contact phone number is present
- Ensure a security contact phone number is present.
- org.openrewrite.terraform.azure.EnsureActivityLogRetentionIsSetTo365DaysOrGreater
- Ensure activity log retention is set to 365 days or greater
- Ensure activity log retention is set to 365 days or greater.
- org.openrewrite.terraform.azure.EnsureAllKeysHaveAnExpirationDate
- Ensure all keys have an expiration date
- Ensure all keys have an expiration date.
- org.openrewrite.terraform.azure.EnsureAppServiceEnablesDetailedErrorMessages
- Ensure app service enables detailed error messages
- Ensure app service enables detailed error messages.
- org.openrewrite.terraform.azure.EnsureAppServiceEnablesFailedRequestTracing
- Ensure app service enables failed request tracing
- Ensure app service enables failed request tracing.
- org.openrewrite.terraform.azure.EnsureAppServiceEnablesHTTPLogging
- Ensure app service enables HTTP logging
- Ensure app service enables HTTP logging.
- org.openrewrite.terraform.azure.EnsureAppServicesUseAzureFiles
- Ensure app services use Azure files
- Ensure app services use Azure files.
- org.openrewrite.terraform.azure.EnsureAzureAppServiceWebAppRedirectsHTTPToHTTPS
- Ensure Azure App Service Web app redirects HTTP to HTTPS
- Ensure Azure App Service Web app redirects HTTP to HTTPS.
- org.openrewrite.terraform.azure.EnsureAzureApplicationGatewayHasWAFEnabled
- Ensure Azure application gateway has WAF enabled
- Ensure Azure application gateway has WAF enabled.
- org.openrewrite.terraform.azure.EnsureAzureKeyVaultIsRecoverable
- Ensure Azure key vault is recoverable
- Ensure Azure key vault is recoverable.
- org.openrewrite.terraform.azure.EnsureAzureNetworkWatcherNSGFlowLogsRetentionIsGreaterThan90Days
- Ensure Azure Network Watcher NSG flow logs retention is greater than 90 days
- Ensure Azure Network Watcher NSG flow logs retention is greater than 90 days.
- org.openrewrite.terraform.azure.EnsureAzurePostgreSQLDatabaseServerWithSSLConnectionIsEnabled
- Ensure Azure PostgreSQL database server with SSL connection is enabled
- Ensure Azure PostgreSQL database server with SSL connection is enabled.
- org.openrewrite.terraform.azure.EnsureAzureSQLServerAuditLogRetentionIsGreaterThan90Days
- Ensure Azure SQL server audit log retention is greater than 90 days
- Ensure Azure SQL server audit log retention is greater than 90 days.
- org.openrewrite.terraform.azure.EnsureAzureSQLServerSendAlertsToFieldValueIsSet
- Ensure Azure SQL server send alerts to field value is set
- Ensure Azure SQL server send alerts to field value is set.
- org.openrewrite.terraform.azure.EnsureAzureSQLServerThreatDetectionAlertsAreEnabledForAllThreatTypes
- Ensure Azure SQL Server threat detection alerts are enabled for all threat types
- Ensure Azure SQL Server threat detection alerts are enabled for all threat types.
- org.openrewrite.terraform.azure.EnsureFTPDeploymentsAreDisabled
- Ensure FTP Deployments are disabled
- Ensure FTP Deployments are disabled.
- org.openrewrite.terraform.azure.EnsureKeyVaultAllowsFirewallRulesSettings
- Ensure key vault allows firewall rules settings
- Ensure key vault allows firewall rules settings.
- org.openrewrite.terraform.azure.EnsureKeyVaultEnablesPurgeProtection
- Ensure key vault enables purge protection
- Ensure key vault enables purge protection.
- org.openrewrite.terraform.azure.EnsureKeyVaultKeyIsBackedByHSM
- Ensure key vault key is backed by HSM
- Ensure key vault key is backed by HSM.
- org.openrewrite.terraform.azure.EnsureKeyVaultSecretsHaveContentTypeSet
- Ensure key vault secrets have
content_typeset - Ensure key vault secrets have
content_typeset.
- Ensure key vault secrets have
- org.openrewrite.terraform.azure.EnsureLogProfileIsConfiguredToCaptureAllActivities
- Ensure log profile is configured to capture all activities
- Ensure log profile is configured to capture all activities.
- org.openrewrite.terraform.azure.EnsureMSSQLServersHaveEmailServiceAndCoAdministratorsEnabled
- Ensure MSSQL servers have email service and co-administrators enabled
- Ensure MSSQL servers have email service and co-administrators enabled.
- org.openrewrite.terraform.azure.EnsureManagedIdentityProviderIsEnabledForAppServices
- Ensure managed identity provider is enabled for app services
- Ensure managed identity provider is enabled for app services.
- org.openrewrite.terraform.azure.EnsureMySQLIsUsingTheLatestVersionOfTLSEncryption
- Ensure MySQL is using the latest version of TLS encryption
- Ensure MySQL is using the latest version of TLS encryption.
- org.openrewrite.terraform.azure.EnsureMySQLServerDatabasesHaveEnforceSSLConnectionEnabled
- Ensure MySQL server databases have Enforce SSL connection enabled
- Ensure MySQL server databases have Enforce SSL connection enabled.
- org.openrewrite.terraform.azure.EnsureMySQLServerDisablesPublicNetworkAccess
- Ensure MySQL server disables public network access
- Ensure MySQL server disables public network access.
- org.openrewrite.terraform.azure.EnsureMySQLServerEnablesGeoRedundantBackups
- Ensure MySQL server enables geo-redundant backups
- Ensure MySQL server enables geo-redundant backups.
- org.openrewrite.terraform.azure.EnsureMySQLServerEnablesThreatDetectionPolicy
- Ensure MySQL server enables Threat Detection policy
- Ensure MySQL server enables Threat Detection policy.
- org.openrewrite.terraform.azure.EnsurePostgreSQLServerDisablesPublicNetworkAccess
- Ensure PostgreSQL server disables public network access
- Ensure PostgreSQL server disables public network access.
- org.openrewrite.terraform.azure.EnsurePostgreSQLServerEnablesInfrastructureEncryption
- Ensure PostgreSQL server enables infrastructure encryption
- Ensure PostgreSQL server enables infrastructure encryption.
- org.openrewrite.terraform.azure.EnsurePostgreSQLServerEnablesThreatDetectionPolicy
- Ensure PostgreSQL server enables Threat Detection policy
- Ensure PostgreSQL server enables Threat Detection policy.
- org.openrewrite.terraform.azure.EnsurePublicNetworkAccessEnabledIsSetToFalseForMySQLServers
- Ensure public network access enabled is set to False for mySQL servers
- Ensure public network access enabled is set to False for mySQL servers.
- org.openrewrite.terraform.azure.EnsureSendEmailNotificationForHighSeverityAlertsIsEnabled
- Ensure Send email notification for high severity alerts is enabled
- Ensure Send email notification for high severity alerts is enabled.
- org.openrewrite.terraform.azure.EnsureSendEmailNotificationForHighSeverityAlertsToAdminsIsEnabled
- Ensure Send email notification for high severity alerts to admins is enabled
- Ensure Send email notification for high severity alerts to admins is enabled.
- org.openrewrite.terraform.azure.EnsureStandardPricingTierIsSelected
- Ensure standard pricing tier is selected
- Ensure standard pricing tier is selected.
- org.openrewrite.terraform.azure.EnsureStorageAccountUsesLatestTLSVersion
- Ensure storage account uses latest TLS version
- Communication between an Azure Storage account and a client application is encrypted using Transport Layer Security (TLS). Microsoft recommends using the latest version of TLS for all your Microsoft Azure App Service web applications.
- org.openrewrite.terraform.azure.EnsureTheStorageContainerStoringActivityLogsIsNotPubliclyAccessible
- Ensure the storage container storing activity logs is not publicly accessible
- Ensure the storage container storing activity logs is not publicly accessible.
- org.openrewrite.terraform.azure.EnsureWebAppHasIncomingClientCertificatesEnabled
- Ensure Web App has incoming client certificates enabled
- Ensure Web App has incoming client certificates enabled.
- org.openrewrite.terraform.azure.EnsureWebAppUsesTheLatestVersionOfHTTP
- Ensure Web App uses the latest version of HTTP
- Ensure Web App uses the latest version of HTTP.
- org.openrewrite.terraform.azure.EnsureWebAppUsesTheLatestVersionOfTLSEncryption
- Ensure Web App uses the latest version of TLS encryption
- Ensure Web App uses the latest version of TLS encryption.
- org.openrewrite.terraform.azure.SetAzureStorageAccountDefaultNetworkAccessToDeny
- Set Azure Storage Account default network access to deny
- Ensure Azure Storage Account default network access is set to Deny.
- org.openrewrite.terraform.gcp.EnablePodSecurityPolicyControllerOnGKEClusters
- Enable
PodSecurityPolicycontroller on Google Kubernetes Engine (GKE) clusters - Ensure
PodSecurityPolicycontroller is enabled on Google Kubernetes Engine (GKE) clusters.
- Enable
- org.openrewrite.terraform.gcp.EnableVPCFlowLogsAndIntranodeVisibility
- Enable VPC flow logs and intranode visibility
- Enable VPC flow logs and intranode visibility.
- org.openrewrite.terraform.gcp.EnableVPCFlowLogsForSubnetworks
- Enable VPC Flow Logs for subnetworks
- Ensure GCP VPC flow logs for subnets are enabled. Flow Logs capture information on IP traffic moving through network interfaces. This information can be used to monitor anomalous traffic and provide security insights.
- org.openrewrite.terraform.gcp.EnsureBinaryAuthorizationIsUsed
- Ensure binary authorization is used
- Ensure binary authorization is used.
- org.openrewrite.terraform.gcp.EnsureComputeInstancesLaunchWithShieldedVMEnabled
- Ensure compute instances launch with shielded VM enabled
- Ensure compute instances launch with shielded VM enabled.
- org.openrewrite.terraform.gcp.EnsureGCPCloudStorageBucketWithUniformBucketLevelAccessAreEnabled
- Ensure GCP cloud storage bucket with uniform bucket-level access are enabled
- Ensure GCP cloud storage bucket with uniform bucket-level access are enabled.
- org.openrewrite.terraform.gcp.EnsureGCPKubernetesClusterNodeAutoRepairConfigurationIsEnabled
- Ensure GCP Kubernetes cluster node auto-repair configuration is enabled
- Ensure GCP Kubernetes cluster node auto-repair configuration is enabled.
- org.openrewrite.terraform.gcp.EnsureGCPKubernetesEngineClustersHaveLegacyComputeEngineMetadataEndpointsDisabled
- Ensure GCP Kubernetes engine clusters have legacy compute engine metadata endpoints disabled
- Ensure GCP Kubernetes engine clusters have legacy compute engine metadata endpoints disabled.
- org.openrewrite.terraform.gcp.EnsureGCPVMInstancesHaveBlockProjectWideSSHKeysFeatureEnabled
- Ensure GCP VM instances have block project-wide SSH keys feature enabled
- Ensure GCP VM instances have block project-wide SSH keys feature enabled.
- org.openrewrite.terraform.gcp.EnsureIPForwardingOnInstancesIsDisabled
- Ensure IP forwarding on instances is disabled
- Ensure IP forwarding on instances is disabled.
- org.openrewrite.terraform.gcp.EnsurePrivateClusterIsEnabledWhenCreatingKubernetesClusters
- Ensure private cluster is enabled when creating Kubernetes clusters
- Ensure private cluster is enabled when creating Kubernetes clusters.
- org.openrewrite.terraform.gcp.EnsureSecureBootForShieldedGKENodesIsEnabled
- Ensure secure boot for shielded GKE nodes is enabled
- Ensure secure boot for shielded GKE nodes is enabled.
- org.openrewrite.terraform.gcp.EnsureShieldedGKENodesAreEnabled
- Ensure shielded GKE nodes are enabled
- Ensure shielded GKE nodes are enabled.
- org.openrewrite.terraform.gcp.EnsureTheGKEMetadataServerIsEnabled
- Ensure the GKE metadata server is enabled
- Ensure the GKE metadata server is enabled.
- org.openrewrite.terraform.gcp.GCPBestPractices
- Best practices for GCP
- Securely operate on Google Cloud Platform.
- org.openrewrite.terraform.search.FindRequiredProvider
- Find required providers
- Find
required_providersblocks in Terraform configuration files. Produces a data table of the provider names and their versions.
- org.openrewrite.terraform.search.FindResource
- Find Terraform resource
- Find a Terraform resource by resource type.
- org.openrewrite.terraform.terraform012.RemoveInterpolationOnlyExpressions
- Remove interpolation-only expressions
- Remove unnecessary interpolation expressions like
"$\{var.foo\}"in favor of first-class expression syntaxvar.foo, as supported in Terraform 0.12+.
- org.openrewrite.terraform.terraform012.ReplaceDeprecatedCollectionFunctions
- Replace deprecated
list()andmap()functions - In Terraform 0.12+, the
list()function is replaced by[...]tuple syntax and themap()function is replaced by\{...\}object syntax.
- Replace deprecated
- org.openrewrite.terraform.terraform012.UnquoteTypeConstraints
- Unquote variable type constraints
- In Terraform 0.12+, variable type constraints should be bare types instead of quoted strings. For example,
type = "string"becomestype = string.
- org.openrewrite.terraform.terraform012.UpgradeTerraformTo0_12
- Upgrade Terraform to 0.12
- Migrate Terraform configuration from 0.11 (HCL1) to 0.12 (HCL2) syntax. Removes interpolation-only expressions, unquotes type constraints, replaces deprecated collection functions, and fixes legacy index syntax.
- org.openrewrite.terraform.terraform013.UpgradeRequiredProvidersSyntax
- Upgrade
required_providersto object syntax - In Terraform 0.13+,
required_providersentries should use the object syntax with explicitsourceandversionattributes instead of a plain version string. For example,aws = "~> 3.0"becomesaws = \{ source = "hashicorp/aws", version = "~> 3.0" \}.
- Upgrade
- org.openrewrite.terraform.terraform013.UpgradeTerraformTo0_13
- Upgrade Terraform to 0.13
- Migrate Terraform configuration from 0.12 to 0.13 syntax. Upgrades
required_providersentries from shorthand version strings to the object syntax with explicitsourceandversionattributes.
- org.openrewrite.terraform.terraform015.FindRemovedProvisioners
- Find removed provisioners
- Find usage of provisioners that were removed in Terraform 0.15:
chef,habitat,puppet, andsalt-masterless.
- org.openrewrite.terraform.terraform015.UpgradeTerraformTo0_15
- Upgrade Terraform to 0.15
- Migrate Terraform configuration from 0.14 to 0.15. Finds usage of provisioners that were removed in Terraform 0.15:
chef,habitat,puppet, andsalt-masterless.