tools

Miscellaneous software tools
git clone https://git.omkov.net/tools
git clone [email protected]:tools
Log | Tree | Refs | Download

AuthorJakob Wakeling <[email protected]>
Date2024-12-07 03:39:00
Commit493878e1958abc72105d3958020eb6745a5ac74e
Parent5f634e16c3a5cd459a29095b8eb8d2f23a49b119
Branch master

Add the binclude tool

Diffstat

M Makefile | 3 ++-
A src/binclude/go.mod | 3 +++
A src/binclude/main.go | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

3 files changed, 81 insertions, 1 deletions

diff --git a/Makefile b/Makefile
index 9f97603..8e63b2e 100644
--- a/Makefile
+++ b/Makefile
@@ -2,11 +2,12 @@
 all: help
 
 build: ## Build the project
+	@go build -C ./src/binclude -o ../../bin/binclude .
 	@go build -C ./src/cbor -o ../../bin/cbor .
 	@go build -C ./src/unixtime -o ../../bin/unixtime .
 
 test: ## Run unit tests
-	@go tets ./...
+	@go test ./...
 
 help: ## Display help information
 	@grep -E '^[a-zA-Z_-]+:.*?##.*$$' $(MAKEFILE_LIST) | \
diff --git a/src/binclude/go.mod b/src/binclude/go.mod
new file mode 100644
index 0000000..8b48462
--- /dev/null
+++ b/src/binclude/go.mod
@@ -0,0 +1,3 @@
+module binclude
+
+go 1.23
diff --git a/src/binclude/main.go b/src/binclude/main.go
new file mode 100644
index 0000000..331f9c6
--- /dev/null
+++ b/src/binclude/main.go
@@ -0,0 +1,76 @@
+package main
+
+import (
+	"errors"
+	"flag"
+	"fmt"
+	"io"
+	"os"
+	"strings"
+)
+
+var spaces, magiscule bool
+var tabCount, tabWidth, width int
+
+func main() {
+	flag.BoolVar(&spaces, "spaces", false, "Use spaces instead of tabs for indentation")
+	flag.IntVar(&tabCount, "tabs", 1, "Number of tabs to indent per line")
+	flag.IntVar(&tabWidth, "tab-width", 4, "Number of spaces per tab")
+	flag.IntVar(&width, "width", 120, "Number of characters per line, including indentation")
+	flag.BoolVar(&magiscule, "magiscule", false, "Use uppercase hex digits")
+	flag.Parse()
+
+	if len(flag.Args()) < 1 {
+		fmt.Println("Usage: binclude file...")
+		os.Exit(-1)
+	}
+
+	for _, a := range flag.Args() {
+		if err := binclude(a); err != nil {
+			fmt.Println(err)
+			os.Exit(-1)
+		}
+	}
+}
+
+func binclude(name string) error {
+	file, err := os.Open(name)
+	if err != nil {
+		return err
+	}
+	defer file.Close()
+
+	hexWidth := width - (tabCount * tabWidth)
+	hexCount := ((hexWidth - 5) / 6) + 1
+
+	buf := make([]byte, hexCount)
+	for {
+		n, err := file.Read(buf)
+		if err != nil {
+			if errors.Is(err, io.EOF) {
+				break
+			}
+			return err
+		}
+		if n == 0 {
+			break
+		}
+
+		if spaces {
+			fmt.Print(strings.Repeat(" ", tabCount*tabWidth))
+		} else {
+			fmt.Print(strings.Repeat("\t", tabCount))
+		}
+
+		for i := range n {
+			if magiscule {
+				fmt.Printf("0x%02X, ", buf[i])
+			} else {
+				fmt.Printf("0x%02x, ", buf[i])
+			}
+		}
+		fmt.Println()
+	}
+
+	return nil
+}