Interface-style Functional Pipes in Go

type Op interface {
Do() error
}
type OpFunc func() errorfunc (o OpFunc) Do() error {
return o()
}
type OpFuncs []func() errorfunc (ops OpFuncs) Do() error {
for _, op := range ops {
if err := op(); err != nil {
return err
}
}
return nil
}
import (
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
"gopkg.in/src-d/go-git.v4/plumbing/object"
"github.com/johnstarich/sage/pipe"
)
func initVCS(path string) (*git.Repository, error) {
var err error
var repo *git.Repository
var tree *git.Worktree
var status git.Status
return repo, pipe.OpFuncs{
func() error {
repo, err = git.PlainInit(path, false)
return err
},
func() error {
tree, err = repo.Worktree()
return err
},
func() error {
status, err = tree.Status()
return err
},
func() error {
var ops pipe.OpFuncs
added := false
for file, stat := range status {
// add any untracked files, excluding hidden and tmp files
if stat.Worktree == git.Untracked {
fileCopy := file
ops = append(ops, func() error {
_, err := tree.Add(fileCopy)
return err
})
added = true
}
}
if added {
ops = append(ops, func() error {
_, err := tree.Commit("Initial commit", &git.CommitOptions{
Author: &object.Signature{
Name: "Sage",
When: time.Now(),
},
})
return err
})
}
return ops.Do()
},
}.Do()
}

Written by

Software engineer, hiker. Works on the IBM Cloud Kubernetes Service. Opinions are my own. johnstarich.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store