From 369ad63f282adc11df454bc6cfdf36dfdbc9e145 Mon Sep 17 00:00:00 2001 From: Nick Dumas Date: Mon, 1 May 2023 09:19:54 -0400 Subject: [PATCH] working demo of FSM implementation --- cmd/fsm_demo/main.go | 35 +++++++++++++++++++++++++++++++++++ fsm/fsm.go | 14 +++++++++++++- fsm/nodes.go | 13 +++++++++++-- 3 files changed, 59 insertions(+), 3 deletions(-) create mode 100644 cmd/fsm_demo/main.go diff --git a/cmd/fsm_demo/main.go b/cmd/fsm_demo/main.go new file mode 100644 index 0000000..552e422 --- /dev/null +++ b/cmd/fsm_demo/main.go @@ -0,0 +1,35 @@ +package main + +import ( + "context" + "flag" + + "go.uber.org/zap" + + "code.ndumas.com/ndumas/obsidian-pipeline/fsm" +) + +func main() { + var ( + source, target, attachmentsDir, blogDir string + dev bool + ) + l, _ := zap.NewProduction() + + flag.BoolVar(&dev, "dev", false, "developer mode") + flag.StringVar(&source, "source", "", "source directory containing your vault") + flag.StringVar(&target, "target", "", "target directory containing your hugo site") + flag.StringVar(&attachmentsDir, "attachments", "", "directory containing your vault's attachments") + flag.StringVar(&blogDir, "blog", "", "vault directory containing blog posts to-be-published") + + flag.Parse() + + m := fsm.NewStateMachine(&fsm.NoteFound) + note := "bleep" + ctx := context.WithValue(context.Background(), "note", note) + _, err := m.Transition(ctx, "CopyPost") + if err != nil { + l.Fatal("could not transition from NoteFound to CopyPost", zap.Error(err)) + + } +} diff --git a/fsm/fsm.go b/fsm/fsm.go index bf6f8fd..172ebec 100644 --- a/fsm/fsm.go +++ b/fsm/fsm.go @@ -1,4 +1,4 @@ -package obspipeline +package fsm import ( "context" @@ -6,6 +6,7 @@ import ( ) type State string + type Event string type Action func(ctx context.Context) error @@ -57,3 +58,14 @@ func (m *StateMachine) Transition(ctx context.Context, event Event) (*Node, erro return m.CurrentNode, nil } + +func NewStateMachine(initialNode *Node) *StateMachine { + if initialNode == nil { + return &StateMachine{} + } + + return &StateMachine{ + initialNode: initialNode, + CurrentNode: initialNode, + } +} diff --git a/fsm/nodes.go b/fsm/nodes.go index 3c24354..27e425d 100644 --- a/fsm/nodes.go +++ b/fsm/nodes.go @@ -1,7 +1,13 @@ -package obspipeline +package fsm import ( "context" + + "go.uber.org/zap" +) + +var ( + l, _ = zap.NewProduction() ) var CopyPost = Node{ @@ -28,6 +34,9 @@ var NoteFound = Node{ "CopyPost": &Transition{ Node: &CopyPost, Action: func(ctx context.Context) error { + l = l.Named("NoteFound") + note := ctx.Value("note").(string) + l.Info("creating post from note", zap.String("filename", note)) // scan for attachments here // if len() attachments > 0 // @@ -86,6 +95,6 @@ var SanitizeLinks = Node{ } var Terminate = Node{ - State: "SanitizeLinks", + State: "Terminate", Transitions: map[Event]*Transition{}, }