Formatador
tyrus fmt formata arquivos fonte .tyr a partir da raiz do projeto. O formatter lê tyrus-fmt.json quando ele existe; toda chave é opcional e chaves omitidas usam o default interno.
Comandos
tyrus fmt
tyrus fmt --check
tyrus fmt --stdout src/main.tyr
tyrus fmt --init
tyrus fmt --defaulttyrus fmt reescreve arquivos do projeto no local. --check verifica formatação sem escrever arquivos e é o modo adequado para CI. --stdout imprime a saída formatada para caminhos explícitos. --init cria ou atualiza tyrus-fmt.json adicionando opções ausentes e preservando valores existentes. --default redefine tyrus-fmt.json para a configuração default completa.
Configuração de exemplo
{
"array_expand": "simple",
"blank_lines": "collapse",
"blank_lines_around_blocks": true,
"blank_lines_around_decorations": true,
"brace_spacing": true,
"brace_style": "same-line",
"final_newline": true,
"indent_style": "spaces",
"indent_width": 4,
"imports_sort": true,
"line_width": 80,
"object_expand": "simple",
"pipeline_chain_layout": "line-by-line",
"prefer_arrow_function": false,
"quote_style": "double",
"remove_unused_imports": true,
"trailing_comma": "es5"
}Opções
| Opção | Default | Valores | Finalidade |
|---|---|---|---|
array_expand | "simple" | "simple", "expand-all", "off" | Controla quando arrays literais são expandidos para múltiplas linhas. |
blank_lines | "collapse" | "collapse", "off" | Controla linhas em branco entre imports, declarações, statements e blocos de fluxo. |
blank_lines_around_blocks | true | true, false | Adiciona linhas em branco antes e depois de statements de bloco e funções. |
blank_lines_around_decorations | true | true, false | Adiciona separação ao redor de campos decorados em interface/type. |
brace_spacing | true | true, false | Imprime objetos como { x: 1 } ou {x: 1}. |
brace_style | "same-line" | "same-line", "next-line", "off" | Controla chaves de abertura em funções e blocos de controle. |
final_newline | true | true, false | Garante newline final no arquivo. |
indent_style | "spaces" | "spaces", "tab" | Seleciona espaços ou tabs para indentação. |
indent_width | 4 | inteiro >= 0 | Número de espaços por nível quando indent_style é "spaces". |
imports_sort | true | true, false | Ordena imports por caminho de módulo e mantém imports tyrus:* primeiro. |
line_width | 90 | inteiro >= 0 | Expande arrays, objetos, argumentos de chamada e ternários que excedem a largura configurada. |
object_expand | "simple" | "simple", "expand-all", "off" | Controla quando objetos literais são expandidos para múltiplas linhas. |
pipeline_chain_layout | "line-by-line" | "line-by-line", "inline", "off" | Controla o layout de chains com mais de um ` |
prefer_arrow_function | false | true, false | Força toda declaração de função de nível superior para a forma arrow (true), ou mantém cada uma na forma em que foi escrita, misturando function e arrow livremente (false). |
quote_style | "double" | "double", "single", "off" | Seleciona aspas preferidas para strings ou preserva as aspas e escapes originais de cada literal. |
remove_unused_imports | true | true, false | Remove specifiers de import não usados ou declarações inteiras de import não usado. |
trailing_comma | true | true, false | Controla vírgulas finais em arrays e objetos multi-line. |
array_expand
Controla quando arrays literais são expandidos para múltiplas linhas.
{ "array_expand": "simple" }const simple = ["a", "b", "c"];
const complex = [foo(1), bar(2)];With "simple", the first array stays inline because all elements are literals, while the second expands because it contains function calls.
{ "array_expand": "expand-all" }const simple = [
"a",
"b",
"c",
];With "expand-all", every multi-element array expands regardless of complexity.
{ "array_expand": "off" }const values = [firstValue, secondValue];With "off", arrays remain inline even when they exceed line_width.
blank_lines
Controla linhas em branco entre imports, declarações, statements e blocos de controle.
{ "blank_lines": "collapse" }import { readFileSync } from "tyrus:fs";
import { add } from "./math";
function main(): void {
const x = 1;
if (x > 0) {
print("positive");
}
const y = 2;
}With "collapse", blank lines separate imports, declarations, and control-flow blocks.
{ "blank_lines": "off" }import { readFileSync } from "tyrus:fs";
import { add } from "./math";
function main(): void {
const x = 1;
if (x > 0) {
print("positive");
}
const y = 2;
}With "off", the formatter does not add blank lines, and repeated blank lines are collapsed.
blank_lines_around_blocks
Adiciona linhas em branco antes e depois de statements de bloco e declarações de função.
{ "blank_lines_around_blocks": true }function main(): void {
const x = 1;
if (x > 0) {
print("positive");
}
for (let i = 0; i < x; i++) {
print(i);
}
}With true, blank lines surround block statements and function declarations.
{ "blank_lines_around_blocks": false }function main(): void {
const x = 1;
if (x > 0) {
print("positive");
}
for (let i = 0; i < x; i++) {
print(i);
}
}With false, blocks sit directly adjacent to surrounding statements.
blank_lines_around_decorations
blank_lines_around_decorations mantém interfaces com muitos validators fáceis de ler.
interface ProductFilter {
@notEmpty()
query: string;
@min(5)
pageSize: i32;
}brace_spacing
Controla se um espaço é impresso entre chaves e seu conteúdo.
{ "brace_spacing": true }const config = { host: "localhost", port: 8080 };With true, a space separates the braces from their content: { host: "localhost" }.
{ "brace_spacing": false }const config = {host: "localhost", port: 8080};With false, no space is printed: {host: "localhost"}.
brace_style
Controla a posição da chave de abertura em corpos de função e blocos de controle.
{ "brace_style": "same-line" }if (cond) {
foo();
} else {
bar();
}With "same-line", the opening brace stays on the header line.
{ "brace_style": "next-line" }if (cond)
{
foo();
}
else
{
bar();
}With "next-line", the opening brace drops to its own line, and else starts a new line too.
{ "brace_style": "off" }With "off", each code block and continuation keyword keeps its original same-line or next-line layout.
final_newline
Controla se uma newline final é adicionada ao final do arquivo.
{ "final_newline": true }The formatter ensures every file ends with a trailing newline character.
{ "final_newline": false }The formatter omits the trailing newline at the end of the file.
indent_style
Controla o estilo de indentação (espaços ou tabs).
{ "indent_style": "spaces", "indent_width": 4 }function main(): void {
const x = 1;
}{ "indent_style": "tab" }function main(): void {
const x = 1;
}With "tab", a single tab character is used per indentation level.
indent_width
Controla o número de espaços por nível de indentação.
{ "indent_width": 2 }function main(): void {
const x = 1;
if (x > 0) {
print("positive");
}
}{ "indent_width": 4 }function main(): void {
const x = 1;
if (x > 0) {
print("positive");
}
}The number of spaces per level changes from 2 to 4.
imports_sort
Controla se declarações de import são ordenadas alfabeticamente e agrupadas por tipo de origem.
{ "imports_sort": true }import { readFileSync } from "tyrus:fs";
import { add } from "./math";
import { formatDate } from "./utils";With true, tyrus:* imports come first, followed by code imports sorted alphabetically.
{ "imports_sort": false }import { add } from "./math";
import { readFileSync } from "tyrus:fs";
import { formatDate } from "./utils";With false, the original import order from the source file is preserved.
line_width
Largura máxima de linha. Arrays, objetos, argumentos de chamada e ternários que excedem esse limite são expandidos para múltiplas linhas.
{ "line_width": 80 }const user = { name: "Alice", age: 30, email: "[email protected]" };If the line exceeds 80 characters, the formatter expands it:
const user = {
name: "Alice",
age: 30,
email: "[email protected]",
};The same expansion applies to arrays, function-call arguments, and ternary expressions.
object_expand
Controla quando objetos literais são expandidos para múltiplas linhas.
{ "object_expand": "simple" }const simple = { x: 1, y: 2 };
const complex = { x: foo(1), y: bar(2) };With "simple", the first object stays inline because values are literals, while the second expands because values are function calls.
{ "object_expand": "expand-all" }const simple = {
x: 1,
y: 2,
};With "expand-all", every multi-field object expands regardless of value complexity.
{ "object_expand": "off" }const options = { first: firstValue, second: secondValue };With "off", objects remain inline even when they exceed line_width.
prefer_arrow_function
Força toda declaração de função de nível superior para a forma arrow ou preserva a forma original.
{ "prefer_arrow_function": false }function main(): void {
hello();
}
const hello = (): void => {
print("hello");
};With false, the formatter preserves each declaration in its original form, so function and arrow styles can coexist.
{ "prefer_arrow_function": true }const main = (): void => {
hello();
};
const hello = (): void => {
print("hello");
};With true, every top-level function declaration is forced to the arrow form.
quote_style
Seleciona aspas preferidas para strings. Com "off", o formatter preserva as aspas e escapes originais de cada literal de string.
{ "quote_style": "double" }const name = "Alice";{ "quote_style": "single" }const name = 'Alice';{ "quote_style": "off" }const name = 'Alice';
const greeting = "Hello";remove_unused_imports
Remove specifiers de import não usados ou declarações inteiras de import não usado.
{ "remove_unused_imports": true }import { add, subtract } from "./math";
const result = add(1, 2);With true, the unused subtract specifier is removed.
{ "remove_unused_imports": false }import { add, subtract } from "./math";
const result = add(1, 2);With false, unused imports are kept, only their layout is formatted.
trailing_comma
Controla vírgulas finais em arrays e objetos multi-line.
{ "trailing_comma": true }const items = [
"a",
"b",
"c",
];
const config = {
host: "localhost",
port: 8080,
};{ "trailing_comma": false }const items = [
"a",
"b",
"c"
];
const config = {
host: "localhost",
port: 8080
};Com true, vírgulas finais são adicionadas em arrays e objetos multi-line. Com false, nenhuma vírgula final é adicionada.
Antes e depois
import { readFileSync, type FsError } from "tyrus:fs";
const add = (left: i32, right: i32): i32 => left + right;
interface FormatResult { value:i32;source:Result<string,FsError>; }
const main = (): void => {
const result: FormatResult = { value:add(1,2),source:readFileSync("README.md") };
};import { readFileSync, type FsError } from "tyrus:fs";
const add = (left: i32, right: i32): i32 => left + right;
interface FormatResult {
value: i32;
source: Result<string, FsError>;
}
const main = (): void => {
const result: FormatResult = {
value: add(1, 2),
source: readFileSync("README.md"),
};
};Use --check no CI
tyrus fmt --check verifica formatação sem escrever arquivos, então é o comando certo para pull requests e pipelines de release.
pipeline_chain_layout
pipeline_chain_layout é útil para transformações funcionais porque cada etapa continua fácil de escanear.
const result = value
|> normalize
|> validate(%)
|> save(%);Defina como "inline" quando o projeto preferir chains curtas e compactas.
Defina como "off" para preservar se cada chain foi escrita em uma linha ou em múltiplas linhas.
const result = value |> normalize |> validate(%) |> save(%);