move the main package into main.go and move out all the compile logic into the cmd package

This commit is contained in:
Robin Bärtschi 2025-01-22 09:16:59 +01:00
parent 6513c45936
commit 3c3c1fc880
2 changed files with 50 additions and 23 deletions

View File

@ -1,8 +1,7 @@
package main package cmd
import ( import (
"bytes" "bytes"
"flag"
"fmt" "fmt"
"io" "io"
"os" "os"
@ -18,6 +17,14 @@ import (
"robaertschi.xyz/robaertschi/tt/typechecker" "robaertschi.xyz/robaertschi/tt/typechecker"
) )
type Arguments struct {
Output string
Input string
OnlyEmitAsm bool
}
// Prefix writer writes a prefix befor a call to an other writer
// This Prefix is written befor each new line
type prefixWriter struct { type prefixWriter struct {
output io.Writer output io.Writer
outputPrefix []byte outputPrefix []byte
@ -66,27 +73,11 @@ func (w *prefixWriter) Write(p []byte) (n int, err error) {
return return
} }
func main() { func Compile(args Arguments) {
flag.Usage = func() { output := args.Output
fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s [flags] input\nPossible flags:\n", os.Args[0]) input := args.Input
flag.PrintDefaults() onlyEmitAsm := args.OnlyEmitAsm
}
var output string
flag.StringVar(&output, "o", "", "Output a executable named `file`")
flag.StringVar(&output, "output", "", "Output a executable named `file`")
onlyEmitAsm := flag.Bool("S", false, "Only emit the asembly file and exit")
flag.Parse()
input := flag.Arg(0)
if input == "" {
flag.Usage()
os.Exit(1)
}
if output == "" {
output = strings.TrimSuffix(input, filepath.Ext(input))
}
asmOutputName := strings.TrimSuffix(input, filepath.Ext(input)) + ".asm" asmOutputName := strings.TrimSuffix(input, filepath.Ext(input)) + ".asm"
file, err := os.Open(input) file, err := os.Open(input)
@ -158,7 +149,7 @@ func main() {
} }
} }
if !*onlyEmitAsm { if !onlyEmitAsm {
args := []string{asmOutputName, output} args := []string{asmOutputName, output}
cmd := exec.Command(fasmPath, args...) cmd := exec.Command(fasmPath, args...)
cmd.Stdout = NewPrefixWriterString(os.Stdout, "fasm output: ") cmd.Stdout = NewPrefixWriterString(os.Stdout, "fasm output: ")

36
main.go Normal file
View File

@ -0,0 +1,36 @@
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"robaertschi.xyz/robaertschi/tt/cmd"
)
func main() {
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s [flags] input\nPossible flags:\n", os.Args[0])
flag.PrintDefaults()
}
var output string
flag.StringVar(&output, "o", "", "Output a executable named `file`")
flag.StringVar(&output, "output", "", "Output a executable named `file`")
onlyEmitAsm := flag.Bool("S", false, "Only emit the asembly file and exit")
flag.Parse()
input := flag.Arg(0)
if input == "" {
flag.Usage()
os.Exit(1)
}
if output == "" {
output = strings.TrimSuffix(input, filepath.Ext(input))
}
cmd.Compile(cmd.Arguments{Output: output, Input: input, OnlyEmitAsm: *onlyEmitAsm})
}