69 lines
1.3 KiB
Go
69 lines
1.3 KiB
Go
|
package mnt
|
||
|
|
||
|
import (
|
||
|
"github.com/go-errors/errors"
|
||
|
|
||
|
"gensokyo.cafe/xmnt/msg"
|
||
|
)
|
||
|
|
||
|
type Mounter interface {
|
||
|
Mount() error
|
||
|
Unmount() error
|
||
|
}
|
||
|
|
||
|
type (
|
||
|
MounterFunc func(*Preset) (Mounter, error)
|
||
|
MatcherFunc func(string) ([]*Preset, error)
|
||
|
)
|
||
|
|
||
|
var mounters = map[string]MounterFunc{}
|
||
|
|
||
|
func RegisterMounter(typeName string, fn MounterFunc) {
|
||
|
mounters[typeName] = fn
|
||
|
}
|
||
|
|
||
|
func MounterFromPreset(preset *Preset) (Mounter, error) {
|
||
|
if fn, ok := mounters[preset.Type]; !ok {
|
||
|
return nil, errors.Errorf("unknown type %q", preset.Type)
|
||
|
} else {
|
||
|
return fn(preset)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
var matchers []MatcherFunc
|
||
|
|
||
|
func RegisterMatcher(fn MatcherFunc) {
|
||
|
matchers = append(matchers, fn)
|
||
|
}
|
||
|
|
||
|
func MatchAll(s string) ([]*Preset, error) {
|
||
|
// Match against presets. If matched, return the preset (should be only one).
|
||
|
if matches, err := match(s); err != nil {
|
||
|
msg.Errorf("Failed to find match in presets: %v", err)
|
||
|
} else if len(matches) > 0 {
|
||
|
return matches[:1], nil
|
||
|
}
|
||
|
|
||
|
// Run other matchers. Might produce multiple matches.
|
||
|
var ret []*Preset
|
||
|
rCh := make(chan []*Preset, 1)
|
||
|
|
||
|
for _, fn := range matchers {
|
||
|
go func(fn MatcherFunc) {
|
||
|
matches, err := fn(s)
|
||
|
if err != nil {
|
||
|
msg.Errorf("%v", err)
|
||
|
rCh <- nil
|
||
|
} else {
|
||
|
rCh <- matches
|
||
|
}
|
||
|
}(fn)
|
||
|
}
|
||
|
for range matchers {
|
||
|
matches := <-rCh
|
||
|
ret = append(ret, matches...)
|
||
|
}
|
||
|
|
||
|
return ret, nil
|
||
|
}
|