API Reference¶
Lint Rules¶
- class tukuroi.Rule(source, imports)¶
A lint rule.
MESSAGEis the message of a report that gives none; the name of the rule is the name of its class, without a “Rule” at its end.- Parameters:
source (Source)
imports (ImportTable)
- classmethod name()¶
The name of the rule: the name of its class, without “Rule” at its end.
- Return type:
- report(node, message=None, *, replacement=None, edits=(), span=None, unused_imports=())¶
Report a violation at
node, withmessageorMESSAGE. The fix, if any, isreplacementfor the text ofnode, oredits.spanis where the report is, when it is not the span ofnode: for what the tree has no node for, such as an operator (#143). The comments that suppress the report are still those ofnode.unused_importsare the qualified names (such as"typing.NamedTuple") that the fix may leave unused: after the fixes, the engine takes out their imports that no code reads any more (#141).
- class tukuroi.Invalid(code, expected_message=None, expected_replacement=None, position=None)¶
Code that the rule reports. When given, the message, the code after the fix, and the position of the report are checked too.
- Parameters:
- class tukuroi.Edit(span, text)¶
Replace
spanwithtext. An empty span inserts at its place.
- class tukuroi.Position(line, column)¶
A line, counted from 1, and a column in characters, counted from 0.
- class tukuroi.Span(start, end)¶
The offsets
[start, end)into a text. An empty span (start == end) is the place to insert at.
- class tukuroi.Range(start, end)¶
From
starttoend: the positions of a span, to show it.
- class tukuroi.Source(path, text, encoding, bom, tree, lines, tokens, comments)¶
A file read and parsed, with what the rules and the engine need of it.
encodingis the name thattokenize.detect_encodinggives (such as"utf-8"or"iso-8859-1"), orNonewhen the source was made from text.bomis whether the text started with a BOM, whichtextdoes not have.- Parameters:
- span(node)¶
The span of
node, a node oftree. AModulespans the whole text; another node without a position raisesTypeError.
- tokens_in(span)¶
The tokens whose spans are in
span, in their order (#144).
- class tukuroi.Token(type, string, span, start, end)¶
A token of
tokenize: its type (such astokenize.NAME), its string, its span, and the positions of the start and the end of the span (#144). The end of a token past the end of its line, as tokenize gives the line end tokens, is the start of the next line: a span is always in the text.
- class tukuroi.Comment(span, text)¶
A comment: its span, and its text from
#to the end of the line.
- class tukuroi.ImportTable(bindings, _resolved=mappingproxy({}))¶
The qualified names that the imports of a module bind:
bindings, those of the module scope, and the name of each node of the tree, by its scope.- qualified_names(node)¶
The qualified names of
node: a name, or attributes of a name. Any other node, and a name that no import binds in its scope, has none. A name that is not a node of the tree, such as one made by a rule, is taken as a name of the module scope.
Plugins¶
- class tukuroi.FormatterPlugin(*args, **kwargs)¶
A formatter of the files that tukuroi fixes (#169): a class registered in the entry points
tukuroi.formatters, by the name thatformatterof a config gives. tukuroi makes one with no argument.
- class tukuroi.OutputFormatPlugin(config)¶
An output format: a class registered in the entry points
tukuroi.output_formats. tukuroi makes one for a run, with the config of the run (such as itsoutput_template), and prints what it gives: at the start, for each result, and at the end.Noneprints nothing.A format for programs to read, such as one JSON document, sets the class attribute
MACHINE_READABLE = True(#178). tukuroi then prints on the standard output what the format gives, without colors, and nothing else: an error with its traceback, the diff of a fix, the metrics and the prompt offixgo to the standard error, andfix -, whose standard output is the fixed source, is a usage error. Without the attribute, the format is for people to read.- Parameters:
config (Config)
- result(result)¶
What to print for
result: a violation, an error, or a clean file.
Frontends¶
Simple API¶
- tukuroi.tukuroi_paths(paths, *, autofix=False, options=None, parallel=True, metrics_hook=None)¶
Lint multiple files or directories, recursively expanding each path.
Walks all paths given, obeying any
.gitignoreexclusions, finding Python source files. Lints each file found usingtukuroi_file(), using a process pool when more than one file is being linted.Yields
Resultobjects for each path, lint error, or exception found. Seetukuroi_bytes()for semantics.If the first given path is STDIN (
Path("-")), then content will be linted from STDIN usingtukuroi_stdin(). The fixed content will be written to STDOUT. A second path argument may be given, which represents the original content’s true path name, and will be used: - to resolve thetukuroi.tomlconfiguration file(s) - when printing status messages, diffs, or errors. If no second path argument is given, it will default to “stdin” in the current working directory. Any further path names will result in a runtime error. A STDIN after another path is skipped with a warning. The CLI refuses both, as usage errors (#40).Fixes can be sent back to the generator, as with
tukuroi_bytes(), withparallel=Falseonly: in a process pool, sendingTrueraises aValueError(#179).A path that does not exist raises a
FileNotFoundErrorbefore the first result. A file given by name is linted though.gitignorehas it, and a file given twice, by name or in a directory, is linted once (#40).Note
Currently does not support applying individual fixes when
parallel=True, due to limitations in the multiprocessing method in use. Settingparallel=Falsewill enable interactive fixes. Settingautofix=Truewill always apply fixes automatically during linting.When a rule ends the process that lints a file (
os._exit, a crash, a kill), that file gets an error, and the other files their results (#94).Before the first result, the config of the directory of each file is read (
check()): a config that tukuroi cannot use raises aConfigError, and no file is linted (#40). A file linted alone (tukuroi_file()) gets such an error as its result.
- tukuroi.tukuroi_file(path, *, autofix=False, options=None, metrics_hook=None)¶
Lint a single file on disk, detecting and generating appropriate configuration.
Generates a merged Configuration based on all applicable config files. Reads file from disk as raw bytes, and uses
tukuroi_bytes()to lint and apply any fixes to the content. Writes content back to disk if changes are detected.Yields
Resultobjects for each lint error or exception found, or a single empty result if the file is clean. Seetukuroi_bytes()for semantics.
- tukuroi.print_result(result, *, show_diff=False, stderr=False, output=None)¶
Print
result: whatoutput, an output format plugin (#169), gives for it (by default, that oftukuroi), and an exception with its traceback. With a format for programs to read (MACHINE_READABLE), what it gives is printed without colors, and the rest on stderr (#178).Setting
show_diff=Truewill output autofixes or suggested changes in unified diff format, using ANSI colors when possible.Returns
Trueif the result is “dirty” - either a lint error or exception.- Parameters:
result (Result)
show_diff (bool)
stderr (bool)
output (OutputFormatPlugin | None)
- Return type:
- class tukuroi.Violation(rule_name, range, message, autofixable, diff='')¶
A violation that a rule reports: the rule, where it is (lines from 1, columns in characters from 0), the message, whether tukuroi can fix it, and the diff of its fix alone.
- class tukuroi.Result(path, violation, error=None, applied=0, remaining=0)¶
A single lint result for a given file and lint rule. A file whose fixes were applied ends with a result that has only
applied: how many, andremaining: the violations left in the file after them.- Parameters:
- class tukuroi.Error(type, message, traceback='', position=None)¶
An exception that stopped tukuroi on a file, in strings alone: the name of its type and its message, as
tracebackwrites them, and the traceback (empty for a syntax error in the file). The process pool oflintsends it back whatever the exception was, even one that a rule of the repo defines (#64). A syntax error has its position too, which the LSP shows the error at (#96).
Advanced API¶
- tukuroi.tukuroi_bytes(path, content, *, config, autofix=False, metrics_hook=None)¶
Lint raw bytes content representing a single path, using the given configuration.
Yields
Resultobjects for each lint error or exception found, or a single empty result if the file is clean. A file is considered clean if no lint errors or no rules are enabled for the given path. Returns the finalFileContentincluding any fixes applied.Use
capture()to more easily capture return value after iterating through violations. Usegenerator.send(...)with a boolean value to apply individual fixes for each violation.If
autofixisTrue, all violations with replacements will be applied automatically, even ifFalseis sent back to the generator. After the violations of a file whose fixes were applied, a lastResulttells how many were (applied), and how many violations are left in the fixed text (remaining):fixexits with 1 if any are (#40).It runs the new engine (#21). The fixes that
autofixtakes are applied round after round; those sent back to the generator, in one round. The fixed text is formatted withruff formatwhen the config chooses it (#108).A rule of
configthat cannot be loaded is the error of the file, without a traceback, and no rule runs (#40).
- class tukuroi.util.capture(generator)¶
Wrap a generator, and capture it’s final return value in the
resultproperty.Allows sending values back to the generator using the
respond()method.Example usage:
generator = capture( tukuroi_bytes(...) ) for result in generator: # Result ... generator.respond(...) # optional result = generator.result # FileContent
- Parameters:
generator (Generator)
- respond(answer)¶
Send a value back to the generator in the next iteration.
Can be called while iterating on the wrapped generator object.
- Parameters:
answer (Send)
- Return type:
None
- property result: Return¶
Contains the final return value from the wrapped generator, if any.
- class tukuroi.Config(path=<factory>, root=<factory>, enable_root_import=False, custom_rules=True, enable=<factory>, disable=<factory>, formatter='none', output_format='tukuroi', output_template='')¶
Materialized configuration valid for processing a single file.
- Parameters:
- disable: list[QualifiedRule]¶
- enable: list[QualifiedRule]¶
- class tukuroi.Options(debug=None, config_file=None, rules=(), output_format=None, output_template='', print_metrics=False, custom_rules=True)¶
Command-line options to affect runtime behavior
- Parameters:
- rules: Sequence[QualifiedRule] = ()¶