Skip to content

Commit

Permalink
define whole template as go struct, set default title
Browse files Browse the repository at this point in the history
  • Loading branch information
bartolomej committed Sep 7, 2024
1 parent 5877e97 commit d0031ae
Show file tree
Hide file tree
Showing 16 changed files with 535 additions and 3,495 deletions.
82 changes: 70 additions & 12 deletions cmd/seeder/main.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
package main

import (
"encoding/json"
"fmt"
"golang.org/x/text/language"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strings"
"time"

flixv11 "flix-indexer/flix/v1_1"
"github.com/go-git/go-git/v5"
"golang.org/x/text/cases"
)

type Repository struct {
Expand Down Expand Up @@ -96,44 +102,93 @@ func flixGenerate(projectPath, sourceFilePath string) (string, error) {
)
cmd.Dir = projectPath

output, err := cmd.CombinedOutput()
rawTemplate, err := cmd.CombinedOutput()
if err != nil {
return "", fmt.Errorf("failed to run flow-cli: %v, output: %s", err, output)
return "", fmt.Errorf("failed to run flow-cli: %v, rawTemplate: %s", err, rawTemplate)
}

return string(output), nil
template, err := flixv11.NewFromJson(rawTemplate)
if err != nil {
return "", fmt.Errorf("failed to parse template from json: %s", err)
}

existingTitle := template.GetMessage("title", "en-US")
if existingTitle == "" {
template.SetMessage("title", "en-US", humanizeFileName(sourceFilePath))
}

updatedRawTemplate, err := json.MarshalIndent(template, "", "\t")
if err != nil {
return "", fmt.Errorf("failed to marshal template to json: %s", err)
}

return string(updatedRawTemplate), nil
}

func humanizeFileName(filePath string) string {
rawFileName := path.Base(filePath)
rawFileName = strings.ReplaceAll(rawFileName, ".cdc", "")
rawFileName = string(regexp.MustCompile("[_-]").ReplaceAll([]byte(rawFileName), []byte(" ")))
rawFileName = cases.Title(language.English, cases.Compact).String(rawFileName)
return rawFileName
}

func processRepositories(repos []Repository) {
func runEmulator(projectPath string) (*exec.Cmd, error) {
cmd := exec.Command("flow", "emulator")
cmd.Dir = projectPath
cmd.Stdout = os.Stdout

err := cmd.Start()
if err != nil {
return cmd, err
}

return cmd, nil
}

func processRepositories(repos []Repository) error {
for _, repo := range repos {
repoName := filepath.Base(repo.GitUrl)
tempDir := filepath.Join("temp", repoName)
repoDir := filepath.Join("temp", repoName)

emulatorCmd, err := runEmulator(repoDir)
if err != nil {
return err
}
// Wait for emulator to start up
time.Sleep(time.Second)

if _, err := os.Stat(tempDir); os.IsNotExist(err) {
fmt.Printf("Cloning %s into %s...\n", repo.GitUrl, tempDir)
err := cloneRepository(repo.GitUrl, tempDir)
if _, err := os.Stat(repoDir); os.IsNotExist(err) {
fmt.Printf("Cloning %s into %s...\n", repo.GitUrl, repoDir)
err := cloneRepository(repo.GitUrl, repoDir)
if err != nil {
log.Fatalf("Failed to clone repository: %v\n", err)
}
}

for _, interactionPath := range repo.InteractionPaths {
files, err := findFiles(tempDir, interactionPath)
files, err := findFiles(repoDir, interactionPath)
if err != nil {
log.Fatalf("Failed to find files: %v\n", err)
}

for _, file := range files {
if strings.HasSuffix(file, ".cdc") {
processCadenceFile(tempDir, file)
processCadenceFile(repoDir, file)
}
}
}

if cleanupTempFolders {
cleanupDirectory(tempDir)
cleanupDirectory(repoDir)
}

err = emulatorCmd.Process.Kill()
if err != nil {
return err
}
}
return nil
}

func cloneRepository(gitUrl, targetDir string) error {
Expand Down Expand Up @@ -162,5 +217,8 @@ func cleanupDirectory(directory string) {
}

func main() {
processRepositories(repos)
err := processRepositories(repos)
if err != nil {
panic(err)
}
}
14 changes: 7 additions & 7 deletions flix/v1_1/indexer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ import (
)

type TemplateIndexer struct {
store []Template
store []*Template
}

const templatesDirPath = "./templates/"

func NewIndexer() *TemplateIndexer {
return &TemplateIndexer{
store: make([]Template, 0),
store: make([]*Template, 0),
}
}

Expand Down Expand Up @@ -62,18 +62,18 @@ func (i *TemplateIndexer) SeedFromFs() error {
return nil
}

func (i *TemplateIndexer) add(template Template) {
func (i *TemplateIndexer) add(template *Template) {
i.store = append(i.store, template)
}

func (i *TemplateIndexer) List() []Template {
func (i *TemplateIndexer) List() []*Template {
return i.store
}

func (i *TemplateIndexer) GetByID(id string) *Template {
for _, template := range i.store {
if template.ID() == id {
return &template
if template.Id == id {
return template
}
}
return nil
Expand All @@ -86,7 +86,7 @@ func (i *TemplateIndexer) GetBySource(cadenceSource []byte) (*Template, error) {
return nil, err
}
if isMatch {
return &template, nil
return template, nil
}
}
return nil, nil
Expand Down
145 changes: 111 additions & 34 deletions flix/v1_1/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,65 +11,142 @@ import (
)

type Template struct {
astHash []byte
raw []byte
parsed parsedTemplate
FType string `json:"f_type"`
FVersion string `json:"f_version"`
Id string `json:"id"`
Data data `json:"data"`
}

type parsedTemplate struct {
FType string `json:"f_type"`
FVersion string `json:"f_version"`
Id string `json:"id"`
Data parsedData `json:"data"`
type message struct {
Key string `json:"key"`
I18n []i18n `json:"i18n"`
}

type parsedData struct {
Type string `json:"type"`
Cadence parsedCadence `json:"cadence"`
type i18n struct {
Tag string `json:"tag"`
Translation string `json:"translation"`
}

type parsedCadence struct {
Body string `json:"body"`
type data struct {
Type string `json:"type"`
Interface string `json:"interface"`
Cadence cadence `json:"cadence"`
Parameters []parameter `json:"parameters"`
Dependencies []dependencies `json:"dependencies"`
Messages []message `json:"messages"`
}

func NewFromJson(rawJson []byte) (Template, error) {
var parsed parsedTemplate
type dependencies struct {
Contracts []contractDependency `json:"contracts"`
}

type contractDependency struct {
Contracts string `json:"contract"`
Networks []contractNetwork `json:"networks"`
}

type contractNetwork struct {
Network string `json:"network"`
Address string `json:"address"`
DependencyPinBlockHeight int `json:"dependency_pin_block_height"`
DependencyPin dependencyPin `json:"dependency_pin"`
}

type dependencyPin struct {
Pin string `json:"pin"`
PinSelf string `json:"pin_self"`
PinContractName string `json:"pin_contract_name"`
PinContractAddress string `json:"pin_contract_address"`
Imports []dependencyPin `json:"imports"`
}

type parameter struct {
Label string `json:"label"`
Index int `json:"index"`
Type string `json:"type"`
Messages []message `json:"messages"`
}

type cadence struct {
Body string `json:"body"`
NetworkPins []networkPin `json:"network_pins"`
}

type networkPin struct {
Network string `json:"network"`
PinSelf string `json:"pin_self"`
}

func NewFromJson(rawJson []byte) (*Template, error) {
var parsed Template
err := json.Unmarshal(rawJson, &parsed)
if err != nil {
return Template{}, err
return nil, err
}

if parsed.FVersion != "1.1.0" {
return Template{}, fmt.Errorf("unsupported f_version '%s'", parsed.FVersion)
return nil, fmt.Errorf("unsupported f_version '%s'", parsed.FVersion)
}

astHash, err := cadenceAstHash([]byte(parsed.Data.Cadence.Body))
return &parsed, nil
}

func (t *Template) CadenceAstHash() ([]byte, error) {
astHash, err := cadenceAstHash([]byte(t.Data.Cadence.Body))
if err != nil {
return Template{}, err
return nil, err
}

return Template{
astHash: astHash,
raw: rawJson,
parsed: parsed,
}, nil
return astHash, nil
}

func (t Template) ID() string {
return t.parsed.Id
func (t *Template) MatchesSource(source []byte) (bool, error) {
astHash1, err := cadenceAstHash(source)
if err != nil {
return false, err
}

astHash2, err := t.CadenceAstHash()
if err != nil {
return false, err
}

return bytes.Equal(astHash1, astHash2), nil
}

func (t Template) MarshalJSON() ([]byte, error) {
return t.raw, nil
func (t *Template) GetMessage(key, tag string) string {
for _, msg := range t.Messages {
if msg.Key == key {
for _, msgI18n := range msg.I18n {
if msgI18n.Tag == tag {
return msgI18n.Translation
}
}
}
}
return ""
}

func (t Template) MatchesSource(source []byte) (bool, error) {
astHash, err := cadenceAstHash(source)
if err != nil {
return false, err
func (t *Template) SetMessage(key, tag, translation string) {
for _, msg := range t.Messages {
if msg.Key == key {
for _, msgI18n := range msg.I18n {
if msgI18n.Tag == tag {
msgI18n.Translation = translation
return
}
}
}
}

return bytes.Equal(t.astHash, astHash), nil
t.Messages = append(t.Messages, message{
Key: key,
I18n: []i18n{
{
Tag: tag,
Translation: translation,
},
},
})
}

func cadenceAstHash(source []byte) ([]byte, error) {
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ require (
github.com/go-git/go-git/v5 v5.12.0
github.com/onflow/cadence v1.0.0-preview.52
github.com/turbolent/prettier v0.0.0-20220320183459-661cc755135d
golang.org/x/text v0.14.0
)

require (
Expand Down
6 changes: 3 additions & 3 deletions server/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ type HttpServer struct {
}

type ListResponse struct {
Data []v11.Template `json:"data"`
Data []*v11.Template `json:"data"`
}

func (s *HttpServer) Setup() {
Expand All @@ -25,7 +25,7 @@ func (s *HttpServer) Setup() {
w.Header().Set("Access-Control-Allow-Origin", "*")

response := ListResponse{
Data: []v11.Template{},
Data: []*v11.Template{},
}

cadenceBase64 := r.URL.Query().Get("cadence_base64")
Expand All @@ -44,7 +44,7 @@ func (s *HttpServer) Setup() {
}

if match != nil {
response.Data = []v11.Template{*match}
response.Data = []*v11.Template{match}
}

} else {
Expand Down
Loading

0 comments on commit d0031ae

Please sign in to comment.