Skip to content

Commit

Permalink
initialize database on first run
Browse files Browse the repository at this point in the history
  • Loading branch information
tsirysndr committed May 26, 2022
1 parent bddd932 commit 099a01b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
26 changes: 22 additions & 4 deletions mada/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"crypto/sha256"
"embed"
"encoding/json"
"errors"
"fmt"
"log"
"os"
Expand All @@ -12,9 +13,12 @@ import (

"github.com/blevesearch/bleve/v2"
"github.com/everystreet/go-shapefile"
"github.com/mitchellh/go-homedir"
"github.com/twpayne/go-geom"
)

var DATABASE_PATH string = filepath.Join(CreateConfigDir(), "mada.bleve")

type Shape struct {
Type string `json:"type"`
Bbox []float32 `json:"bbox"`
Expand Down Expand Up @@ -56,7 +60,7 @@ type Geometry struct {
//go:embed shp/*
var Assets embed.FS

func Init() {
func Init() (bleve.Index, error) {

index, err := CreateOrOpenBleve()

Expand All @@ -82,16 +86,18 @@ func Init() {
parseShapefile(filename, index)
}

return index, nil
}

func CreateOrOpenBleve() (bleve.Index, error) {
if _, err := os.Stat("mada.bleve"); os.IsNotExist(err) {
if _, err := os.Stat(DATABASE_PATH); os.IsNotExist(err) {
geometryMapping := bleve.NewDocumentDisabledMapping()

mapping := bleve.NewIndexMapping()
mapping.DefaultMapping.AddSubDocumentMapping("geometry", geometryMapping)
return bleve.New("mada.bleve", mapping)
return bleve.New(DATABASE_PATH, mapping)
}
return bleve.Open("mada.bleve")
return bleve.Open(DATABASE_PATH)
}

func parseShapefile(name string, index bleve.Index) {
Expand Down Expand Up @@ -192,3 +198,15 @@ func parseShapefile(name string, index bleve.Index) {
// Err() returns the first error encountered during calls to Record()
scanner.Err()
}

func CreateConfigDir() string {
home, _ := homedir.Dir()
path := filepath.Join(home, ".mada")
if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
err := os.Mkdir(path, os.ModePerm)
if err != nil {
panic(err)
}
}
return path
}
10 changes: 9 additions & 1 deletion mada/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ package mada
import (
"encoding/json"
"fmt"
"os"

"github.com/blevesearch/bleve/v2"
"github.com/blevesearch/bleve/v2/search/highlight/highlighter/ansi"
)

func Search(term string, outputInJSON bool) {
index, err := CreateOrOpenBleve()
index, err := InitializeBleve()

if err != nil {
panic(err)
Expand All @@ -36,3 +37,10 @@ func Search(term string, outputInJSON bool) {

fmt.Println(string(b))
}

func InitializeBleve() (bleve.Index, error) {
if _, err := os.Stat(DATABASE_PATH); os.IsNotExist(err) {
return Init()
}
return bleve.Open(DATABASE_PATH)
}

0 comments on commit 099a01b

Please sign in to comment.