main.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package main
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "log"
  6. "net/rpc/jsonrpc"
  7. "strings"
  8. "github.com/natefinch/pie"
  9. )
  10. // LuaPlugin represents a plugin for Algernon (for Lua)
  11. type LuaPlugin struct{}
  12. const namespace = "Lua"
  13. // --- Plugin functionality ---
  14. func add3(a, b int) int {
  15. // Functionality not otherwise available in Lua goes here
  16. return a + b + 3
  17. }
  18. // --- Lua wrapper code ($0 is replaced with the plugin path) ---
  19. const luacode = `
  20. function add3(a, b)
  21. return CallPlugin("$0", "Add3", a, b)
  22. end
  23. `
  24. // --- Lua help text (will be syntax highlighted) ---
  25. const luahelp = `
  26. add3(number, number) -> number // Adds two numbers and then the number 3
  27. `
  28. // --- Plugin wrapper functions ---
  29. // Add3 is exposed to Algernon
  30. func (LuaPlugin) Add3(jsonargs []byte, response *[]byte) (err error) {
  31. var args []int
  32. err = json.Unmarshal(jsonargs, &args)
  33. if err != nil || len(args) < 2 {
  34. // Could not unmarshal the given arguments, or too few arguments
  35. return errors.New("add3 requires two integer arguments")
  36. }
  37. result := add3(args[0], args[1])
  38. *response, err = json.Marshal(result)
  39. return
  40. }
  41. // --- Plugin functions that must be present ---
  42. // Code is called once when the Plugin function is used in Algernon
  43. func (LuaPlugin) Code(pluginPath string, response *string) error {
  44. *response = strings.ReplaceAll(luacode, "$0", pluginPath)
  45. return nil
  46. }
  47. // Help is called once when the help function is used in Algernon
  48. func (LuaPlugin) Help(_ string, response *string) error {
  49. *response = luahelp
  50. return nil
  51. }
  52. // Called once when the Plugin or CallPlugin function is used in Algernon
  53. func main() {
  54. log.SetPrefix("[plugin log] ")
  55. p := pie.NewProvider()
  56. if err := p.RegisterName(namespace, LuaPlugin{}); err != nil {
  57. log.Fatalf("Failed to register plugin: %s", err)
  58. }
  59. p.ServeCodec(jsonrpc.NewServerCodec)
  60. }