Formateador
tyrus fmt formatea archivos fuente .tyr desde la raíz del proyecto. El formatter lee tyrus-fmt.json cuando existe; cada clave es opcional y las claves omitidas usan el default interno.
Comandos
tyrus fmt
tyrus fmt --check
tyrus fmt --stdout src/main.tyr
tyrus fmt --init
tyrus fmt --defaulttyrus fmt reescribe archivos del proyecto en el lugar. --check verifica formato sin escribir archivos y es el modo adecuado para CI. --stdout imprime la salida formateada para rutas explícitas. --init crea o actualiza tyrus-fmt.json agregando opciones ausentes y preservando valores existentes. --default redefine tyrus-fmt.json a la configuración default completa.
Configuración de ejemplo
{
"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"
}Opciones
| Opción | Default | Valores | Finalidad |
|---|---|---|---|
array_expand | "simple" | "simple", "expand-all", "off" | Controla cuándo los arrays literales se expanden a varias líneas. |
blank_lines | "collapse" | "collapse", "off" | Controla líneas en blanco entre imports, declaraciones, statements y bloques de flujo. |
blank_lines_around_blocks | true | true, false | Agrega líneas en blanco antes y después de statements de bloque y funciones. |
blank_lines_around_decorations | true | true, false | Agrega separación alrededor de campos decorados en interface/type. |
brace_spacing | true | true, false | Imprime objetos como { x: 1 } o {x: 1}. |
brace_style | "same-line" | "same-line", "next-line", "off" | Controla llaves de apertura en funciones y bloques de control. |
final_newline | true | true, false | Garantiza newline final en el archivo. |
indent_style | "spaces" | "spaces", "tab" | Selecciona espacios o tabs para indentación. |
indent_width | 4 | entero >= 0 | Número de espacios por nivel cuando indent_style es "spaces". |
imports_sort | true | true, false | Ordena imports por ruta de módulo y mantiene imports tyrus:* primero. |
line_width | 90 | entero >= 0 | Expande arrays, objetos, argumentos de llamada y ternarios que exceden el ancho configurado. |
object_expand | "simple" | "simple", "expand-all", "off" | Controla cuándo los objetos literales se expanden a varias líneas. |
pipeline_chain_layout | "line-by-line" | "line-by-line", "inline", "off" | Controla el layout de chains con más de un ` |
prefer_arrow_function | false | true, false | Fuerza toda declaración de función de nivel superior a la forma arrow (true), o mantiene cada una en la forma en que fue escrita, mezclando function y arrow libremente (false). |
quote_style | "double" | "double", "single", "off" | Selecciona comillas preferidas para strings o preserva las comillas y escapes originales de cada literal. |
remove_unused_imports | true | true, false | Elimina specifiers de import no usados o declaraciones completas de import no usado. |
trailing_comma | true | true, false | Controla comas finales en arrays y objetos multi-line. |
array_expand
Controla cuándo los arrays literales se expanden a varias líneas.
{ "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 líneas en blanco entre imports, declaraciones, statements y bloques de control.
{ "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
Agrega líneas en blanco antes y después de statements de bloque y declaraciones de función.
{ "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 mantiene interfaces con muchos validators fáciles de leer.
interface ProductFilter {
@notEmpty()
query: string;
@min(5)
pageSize: i32;
}brace_spacing
Controla si se imprime un espacio entre llaves y su contenido.
{ "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 la posición de la llave de apertura en cuerpos de función y bloques de control.
{ "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 si se agrega un newline final al final del archivo.
{ "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 el estilo de indentación (espacios o 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 el número de espacios por nivel de indentación.
{ "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 si las declaraciones de import se ordenan alfabéticamente y se agrupan por tipo de origen.
{ "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
Ancho máximo de línea. Arrays, objetos, argumentos de llamada y ternarios que exceden este límite se expanden a varias líneas.
{ "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 cuándo los objetos literales se expanden a varias líneas.
{ "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
Fuerza toda declaración de función de nivel superior a la forma arrow o preserva la 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
Selecciona comillas preferidas para strings. Con "off", el formateador preserva las comillas y escapes originales de cada literal de cadena.
{ "quote_style": "double" }const name = "Alice";{ "quote_style": "single" }const name = 'Alice';{ "quote_style": "off" }const name = 'Alice';
const greeting = "Hello";remove_unused_imports
Elimina specifiers de import no usados o declaraciones completas de import no 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 comas finales en arrays y 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
};Con true, se agregan comas finales en arrays y objetos multi-line. Con false, no se agrega ninguna coma final.
Antes y después
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"),
};
};Usa --check en CI
tyrus fmt --check verifica formato sin escribir archivos, así que es el comando correcto para pull requests y pipelines de release.
pipeline_chain_layout
pipeline_chain_layout es útil para transformaciones funcionales porque cada paso sigue siendo fácil de revisar.
const result = value
|> normalize
|> validate(%)
|> save(%);Defínelo como "inline" cuando el proyecto prefiera chains cortas y compactas.
Defínelo como "off" para preservar si cada chain fue escrita en una línea o en varias líneas.
const result = value |> normalize |> validate(%) |> save(%);