featurebase/ctl/rbf_dump.go
Lory Cloutier f627199acb FB-1766: cleaning up the CmdIO objects passing alternate stdin/
stdout/stderr around

A lot of functions in the cmd and ctl packages were passing these
around and barely using them. Replaced them with a logger for most
functions. Some functions get an io.Writer instead so that their
tests can find the output they're looking for.

More cleanup on fb-1766: reworked the tests that were using io.Pipe
or os.Pipe to check their results so they now use a bytes.Buffer.

Unexported some variables that didn't need to be exported.
Fixed NewConfigCommand to use the provided stderr, not os.Stderr.
Added tests for rbf_dump, rbf_page, and keygen, since those weren't
being tested at all.

Added chksum_test, final cleanup.
2022-11-29 12:49:36 -06:00

101 lines
2 KiB
Go

// Copyright 2021 Molecula Corp. All rights reserved.
package ctl
import (
"context"
"encoding/hex"
"fmt"
"io"
"os"
"strings"
"github.com/molecula/featurebase/v3/logger"
"github.com/molecula/featurebase/v3/rbf"
)
// RBFDumpCommand represents a command for dumping raw data for an RBF page.
type RBFDumpCommand struct {
// Filepath to the RBF database.
Path string
// Page numbers to print.
Pgnos []uint32
// Standard input/output
stdout io.Writer
logDest logger.Logger
}
// NewRBFDumpCommand returns a new instance of RBFDumpCommand.
func NewRBFDumpCommand(logdest logger.Logger) *RBFDumpCommand {
return &RBFDumpCommand{
stdout: os.Stdout,
logDest: logdest,
}
}
// Run executes the export.
func (cmd *RBFDumpCommand) Run(ctx context.Context) error {
// Open database.
db := rbf.NewDB(cmd.Path, nil)
if err := db.Open(); err != nil {
return err
}
defer db.Close()
// Execute with a transaction.
tx, err := db.Begin(false)
if err != nil {
return err
}
defer tx.Rollback()
// Fetch each page & dump.
for _, pgno := range cmd.Pgnos {
buf, err := tx.PageData(pgno)
if err != nil {
return err
}
fmt.Fprintf(cmd.stdout, "## PAGE %d\n", pgno)
fmt.Fprintln(cmd.stdout, compressedHexDump(buf))
fmt.Fprintln(cmd.stdout, "")
}
return nil
}
func compressedHexDump(b []byte) string {
const prefixN = len("00000000")
var output []string
var prev string
var ellipsis bool
lines := strings.Split(strings.TrimSpace(hex.Dump(b)), "\n")
for i, line := range lines {
// Add line to output if it is not repeating or the last line.
if i == 0 || i == len(lines)-1 || trimPrefixN(line, prefixN) != trimPrefixN(prev, prefixN) {
output = append(output, line)
prev, ellipsis = line, false
continue
}
// Add an ellipsis for the first duplicate line.
if !ellipsis {
output = append(output, "...")
ellipsis = true
continue
}
}
return strings.Join(output, "\n")
}
// trimPrefixN trims n bytes from the beginning of a string.
func trimPrefixN(s string, n int) string {
if len(s) < n {
return ""
}
return s[n:]
}