2024-12-18 14:06:21 +01:00
|
|
|
package output
|
|
|
|
|
|
|
|
|
|
import (
|
2024-12-19 09:04:55 +01:00
|
|
|
"encoding/json"
|
2024-12-18 14:06:21 +01:00
|
|
|
"fmt"
|
|
|
|
|
"io"
|
|
|
|
|
"os"
|
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
|
|
"github.com/tlinden/anydb/app"
|
|
|
|
|
"github.com/tlinden/anydb/cfg"
|
|
|
|
|
"golang.org/x/term"
|
|
|
|
|
)
|
|
|
|
|
|
2024-12-19 09:04:55 +01:00
|
|
|
func Print(writer io.Writer, conf *cfg.Config, attr *app.DbAttr, entry *app.DbEntry) error {
|
|
|
|
|
if attr.File != "" {
|
2024-12-20 11:55:07 +01:00
|
|
|
return WriteFile(writer, conf, attr, entry)
|
2024-12-18 14:06:21 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
isatty := term.IsTerminal(int(os.Stdout.Fd()))
|
2024-12-19 09:04:55 +01:00
|
|
|
|
|
|
|
|
switch conf.Mode {
|
2024-12-20 11:53:09 +01:00
|
|
|
case "simple", "":
|
2024-12-19 09:04:55 +01:00
|
|
|
if len(entry.Bin) > 0 {
|
|
|
|
|
if isatty {
|
|
|
|
|
fmt.Println("binary data omitted")
|
|
|
|
|
} else {
|
|
|
|
|
os.Stdout.Write(entry.Bin)
|
|
|
|
|
}
|
2024-12-18 14:06:21 +01:00
|
|
|
} else {
|
2024-12-19 09:04:55 +01:00
|
|
|
fmt.Print(entry.Value)
|
2024-12-18 14:06:21 +01:00
|
|
|
|
2024-12-19 09:04:55 +01:00
|
|
|
if !strings.HasSuffix(entry.Value, "\n") {
|
|
|
|
|
// always add a terminal newline
|
|
|
|
|
fmt.Println()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
case "json":
|
|
|
|
|
jsonentry, err := json.Marshal(entry)
|
|
|
|
|
if err != nil {
|
2024-12-19 10:55:39 +01:00
|
|
|
return fmt.Errorf("failed to marshall json: %s", err)
|
2024-12-18 14:06:21 +01:00
|
|
|
}
|
2024-12-19 09:04:55 +01:00
|
|
|
|
|
|
|
|
fmt.Println(string(jsonentry))
|
|
|
|
|
case "wide":
|
2024-12-19 11:05:26 +01:00
|
|
|
return ListTable(writer, conf, app.DbEntries{*entry})
|
2024-12-20 11:53:09 +01:00
|
|
|
case "template":
|
|
|
|
|
return ListTemplate(writer, conf, app.DbEntries{*entry})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func WriteFile(writer io.Writer, conf *cfg.Config, attr *app.DbAttr, entry *app.DbEntry) error {
|
|
|
|
|
fd, err := os.OpenFile(attr.File, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return fmt.Errorf("failed to open file %s for writing: %w", attr.File, err)
|
|
|
|
|
}
|
|
|
|
|
defer fd.Close()
|
|
|
|
|
|
|
|
|
|
if len(entry.Bin) > 0 {
|
|
|
|
|
// binary file content
|
|
|
|
|
_, err = fd.Write(entry.Bin)
|
|
|
|
|
} else {
|
|
|
|
|
val := entry.Value
|
|
|
|
|
if !strings.HasSuffix(val, "\n") {
|
|
|
|
|
// always add a terminal newline
|
|
|
|
|
val += "\n"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_, err = fd.Write([]byte(val))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
return fmt.Errorf("failed to write to file %s: %w", attr.File, err)
|
2024-12-18 14:06:21 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|