github.com/xhghs/rclone@v1.51.1-0.20200430155106-e186a28cced8/fs/rc/registry.go (about) 1 // Define the registry 2 3 package rc 4 5 import ( 6 "context" 7 "sort" 8 "strings" 9 "sync" 10 11 "github.com/rclone/rclone/fs" 12 ) 13 14 // Func defines a type for a remote control function 15 type Func func(ctx context.Context, in Params) (out Params, err error) 16 17 // Call defines info about a remote control function and is used in 18 // the Add function to create new entry points. 19 type Call struct { 20 Path string // path to activate this RC 21 Fn Func `json:"-"` // function to call 22 Title string // help for the function 23 AuthRequired bool // if set then this call requires authorisation to be set 24 Help string // multi-line markdown formatted help 25 } 26 27 // Registry holds the list of all the registered remote control functions 28 type Registry struct { 29 mu sync.RWMutex 30 call map[string]*Call 31 } 32 33 // NewRegistry makes a new registry for remote control functions 34 func NewRegistry() *Registry { 35 return &Registry{ 36 call: make(map[string]*Call), 37 } 38 } 39 40 // Add a call to the registry 41 func (r *Registry) Add(call Call) { 42 r.mu.Lock() 43 defer r.mu.Unlock() 44 call.Path = strings.Trim(call.Path, "/") 45 call.Help = strings.TrimSpace(call.Help) 46 fs.Debugf(nil, "Adding path %q to remote control registry", call.Path) 47 r.call[call.Path] = &call 48 } 49 50 // Get a Call from a path or nil 51 func (r *Registry) Get(path string) *Call { 52 r.mu.RLock() 53 defer r.mu.RUnlock() 54 return r.call[path] 55 } 56 57 // List of all calls in alphabetical order 58 func (r *Registry) List() (out []*Call) { 59 r.mu.RLock() 60 defer r.mu.RUnlock() 61 var keys []string 62 for key := range r.call { 63 keys = append(keys, key) 64 } 65 sort.Strings(keys) 66 for _, key := range keys { 67 out = append(out, r.call[key]) 68 } 69 return out 70 } 71 72 // Calls is the global registry of Call objects 73 var Calls = NewRegistry() 74 75 // Add a function to the global registry 76 func Add(call Call) { 77 Calls.Add(call) 78 }