Files
go-nkode/sqlite-init/sqlite_init.go

139 lines
2.9 KiB
Go

package main
import (
"database/sql"
"encoding/json"
"fmt"
_ "github.com/mattn/go-sqlite3" // Import the SQLite3 driver
"go-nkode/sql-driver"
"io/ioutil"
"log"
"path/filepath"
"strings"
)
type Icon struct {
Body string `json:"body"`
Width *int `json:"width,omitempty"`
}
// Define the Root struct to represent the entire JSON structure
type Root struct {
Prefix string `json:"prefix"`
Icons map[string]Icon `json:"icons"`
Height int `json:"height"`
}
func main() {
dbPaths := []string{"test.db", "nkode.db"}
outputStr := MakeSvgFiles()
for _, path := range dbPaths {
sql_driver.MakeTables(path)
SaveToSqlite(path, outputStr)
}
}
func SaveToSqlite(dbPath string, outputStr string) {
db, err := sql.Open("sqlite3", dbPath)
if err != nil {
log.Fatal(err)
}
defer db.Close()
lines := strings.Split(outputStr, "\n")
insertSql := `
INSERT INTO svg_icon (svg)
VALUES (?)
`
for _, line := range lines {
if line == "" {
continue
}
_, err := db.Exec(insertSql, line)
if err != nil {
log.Fatal(err)
}
}
}
func MakeSvgFiles() string {
jsonFiles, err := GetAllFiles("./sqlite-init/json")
if err != nil {
log.Fatalf("Error getting JSON files: %v", err)
}
if len(jsonFiles) == 0 {
log.Fatal("No JSON files found in ./json folder")
}
var outputStr string
strSet := make(map[string]struct{})
for _, filename := range jsonFiles {
fileData, err := LoadJson(filename)
if err != nil {
log.Print("Error loading JSON file: ", err)
continue
}
height := fileData.Height
for name, icon := range fileData.Icons {
width := height
parts := strings.Split(name, "-")
if len(parts) <= 0 {
log.Print(name, " has no parts")
continue
}
part0 := parts[0]
_, exists := strSet[part0]
if exists {
continue
}
if icon.Width != nil {
width = *icon.Width
}
strSet[part0] = struct{}{}
if icon.Body == "" {
continue
}
outputStr = fmt.Sprintf("%s<svg viewBox=\"0 0 %d %d\" xmlns=\"http://www.w3.org/2000/svg\">%s</svg>\n", outputStr, width, height, icon.Body)
}
}
return outputStr
}
func GetAllFiles(dir string) ([]string, error) {
// Use ioutil.ReadDir to list all files in the directory
files, err := ioutil.ReadDir(dir)
if err != nil {
return nil, fmt.Errorf("unable to read directory: %v", err)
}
// Create a slice to hold the JSON filenames
var jsonFiles []string
// Loop through the files and filter out JSON files
for _, file := range files {
if !file.IsDir() && filepath.Ext(file.Name()) == ".json" {
jsonFiles = append(jsonFiles, filepath.Join(dir, file.Name()))
}
}
return jsonFiles, nil
}
func LoadJson(filename string) (*Root, error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to read file %s: %v", filename, err)
}
var root Root
err = json.Unmarshal(data, &root)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal JSON: %v", err)
}
return &root, nil
}