github.com/rclone/rclone@v1.66.1-0.20240517100346-7b89735ae726/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 12 // Func defines a type for a remote control function 13 type Func func(ctx context.Context, in Params) (out Params, err error) 14 15 // Call defines info about a remote control function and is used in 16 // the Add function to create new entry points. 17 type Call struct { 18 Path string // path to activate this RC 19 Fn Func `json:"-"` // function to call 20 Title string // help for the function 21 AuthRequired bool // if set then this call requires authorisation to be set 22 Help string // multi-line markdown formatted help 23 NeedsRequest bool // if set then this call will be passed the original request object as _request 24 NeedsResponse bool // if set then this call will be passed the original response object as _response 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) // disabled to make initialization less verbose 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 }