Skip to content

Latest commit

 

History

History
273 lines (221 loc) · 6.48 KB

File metadata and controls

273 lines (221 loc) · 6.48 KB

Feature: Argumentos de Línea de Comandos

Implementación

Fas ahora acepta un argumento de línea de comandos para abrir o crear un archivo al inicio, igual que Vim.

Uso

# Abrir archivo existente
swift run Fas archivo.txt

# Crear archivo nuevo
swift run Fas nuevo.txt

# Iniciar sin archivo
swift run Fas

Comportamiento

Caso 1: Archivo Existente

swift run Fas README.md

Resultado:

  • ✅ Abre el archivo README.md
  • ✅ Carga el contenido en el buffer
  • ✅ Asigna filePath al buffer
  • ✅ Mensaje: "Opened: README.md"
  • ✅ Puedes editar inmediatamente
  • :w guarda sin pedir nombre

Caso 2: Archivo Nuevo (No Existe)

swift run Fas nuevo.txt

Resultado:

  • ✅ Crea un buffer vacío
  • ✅ Asigna filePath = "nuevo.txt" al buffer
  • ✅ Mensaje: "nuevo.txt" [New File]
  • ✅ Puedes empezar a escribir inmediatamente (i)
  • :w guarda en "nuevo.txt" sin pedir nombre
  • ✅ El archivo se crea cuando guardas por primera vez

Caso 3: Sin Argumento

swift run Fas

Resultado:

  • ✅ Inicia con buffer vacío
  • ✅ No hay filePath asignado
  • ✅ Mensaje: "Welcome to Fas! Press 'i' to insert, ':' for commands, ':q' to quit"
  • :w pide nombre de archivo
  • :w archivo.txt asigna nombre y guarda

Cambios Implementados

1. App.swift

@main struct EntryPoint {
    static func main() async throws {
        // Obtener argumentos de línea de comandos
        let arguments = CommandLine.arguments

        // arguments[0] es el nombre del programa, arguments[1] es el primer argumento
        let filePath: String? = arguments.count > 1 ? arguments[1] : nil

        try await Fas.run(withFile: filePath)
    }
}

2. Fas.swift - run()

public static func run(withFile filePath: String? = nil) async throws {
    var editor = Fas()
    try await editor.start(withFile: filePath)
}

3. Fas.swift - start()

private mutating func start(withFile filePath: String?) async throws {
    // ... setup de terminal ...

    // Si se proporcionó un archivo, intentar abrirlo o crear uno nuevo
    if let path = filePath {
        try openOrCreateFile(path)
    }

    // Mensaje de bienvenida solo si no hay archivo
    if filePath == nil {
        state.setMessage("Welcome to Fas! Press 'i' to insert, ':' for commands, ':q' to quit")
    }

    // ... event loop ...
}

4. Nuevo método: openOrCreateFile()

private mutating func openOrCreateFile(_ path: String) throws {
    let expandedPath = (path as NSString).expandingTildeInPath

    // Verificar si el archivo existe
    if FileManager.default.fileExists(atPath: expandedPath) {
        // Si existe, abrirlo normalmente
        try openFile(path)
    } else {
        // Si no existe, crear un buffer nuevo con ese nombre
        let fileName = (expandedPath as NSString).lastPathComponent
        var newBuffer = api.buffers.currentBuffer
        newBuffer.filePath = expandedPath
        newBuffer.fileType = detectFileType(path: expandedPath)
        newBuffer.isModified = false  // Nuevo archivo, todavía no modificado

        // Actualizar el buffer
        api.buffers.currentBuffer = newBuffer

        cursor = Cursor()
        state.cursor = cursor.position
        state.setMessage("\"\(fileName)\" [New File]")
    }
}

Ejemplos de Uso

Ejemplo 1: Editar archivo existente

# Crear archivo de prueba
echo "Hello World" > test.txt

# Abrir con Fas
swift run Fas test.txt

# En el editor:
# - El contenido "Hello World" está visible
# - Mensaje: "Opened: test.txt"
# - Presiona 'i' para editar
# - Agrega texto
# - ESC
# - :w (guarda sin pedir nombre)
# - :q

Ejemplo 2: Crear archivo nuevo

# Abrir archivo que no existe
swift run Fas nuevo.txt

# En el editor:
# - Buffer vacío
# - Mensaje: "nuevo.txt" [New File]
# - Presiona 'i'
# - Escribe contenido
# - ESC
# - :w (crea el archivo)
# - :q

# Verificar
cat nuevo.txt  # Muestra el contenido

Ejemplo 3: Workflow completo

# Editar archivo Swift
swift run Fas Sources/FasCore/Fas.swift

# En el editor:
# - Archivo se abre correctamente
# - Navegar con hjkl
# - Hacer cambios (i → editar → ESC)
# - :w (guarda cambios)
# - :q

Ejemplo 4: Rutas con espacios

# Crear archivo con espacios
swift run Fas "Mi Archivo.txt"

# Funciona correctamente:
# - Mensaje: "Mi Archivo.txt" [New File]
# - :w guarda en "Mi Archivo.txt"

Ejemplo 5: Rutas absolutas y relativas

# Ruta relativa
swift run Fas ../test.txt

# Ruta absoluta
swift run Fas /tmp/test.txt

# Home directory
swift run Fas ~/Documents/test.txt

# Todas funcionan correctamente con expandTildeInPath

Comparación con Vim

Comando Vim Fas Estado
vim archivo.txt Abre/crea Abre/crea ✅ Igual
vim Buffer vacío Buffer vacío ✅ Igual
:w después de abrir Guarda sin pedir Guarda sin pedir ✅ Igual
:w en archivo nuevo Crea archivo Crea archivo ✅ Igual
Mensaje [New File] ✅ Igual

Testing Recomendado

Test 1: Abrir archivo existente

echo "test content" > /tmp/test.txt
swift run Fas /tmp/test.txt
# Verificar:
# - Contenido visible
# - Mensaje "Opened: /tmp/test.txt"
# - :w funciona sin pedir nombre

Test 2: Crear archivo nuevo

rm -f /tmp/nuevo.txt  # Asegurar que no existe
swift run Fas /tmp/nuevo.txt
# Verificar:
# - Buffer vacío
# - Mensaje "nuevo.txt" [New File]
# - i → escribir → ESC → :w → archivo se crea

Test 3: Sin argumentos

swift run Fas
# Verificar:
# - Buffer vacío
# - Mensaje de bienvenida
# - :w pide nombre

Test 4: Múltiples argumentos (solo usa el primero)

swift run Fas archivo1.txt archivo2.txt
# Solo abre archivo1.txt (comportamiento esperado)

Estado

Feature completadaBuild exitoso (2.68s) ✅ 0 errores, 0 warnings de Swift

Archivos Modificados

  • Sources/Fas/App.swift - Parseo de argumentos
  • Sources/FasCore/Fas.swift - run(), start(), openOrCreateFile()

Compatibilidad

  • ✅ Compatible con rutas relativas
  • ✅ Compatible con rutas absolutas
  • ✅ Compatible con ~ (home directory)
  • ✅ Compatible con espacios en nombres
  • ✅ Retrocompatible (sin argumentos sigue funcionando)

Próximas Mejoras Opcionales

  1. Soportar múltiples archivos: fas file1.txt file2.txt
  2. Flags: fas -R archivo.txt (read-only)
  3. Posicionamiento: fas +10 archivo.txt (ir a línea 10)
  4. Tabs: fas -p file1.txt file2.txt (abrir en tabs)