leakybucket.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package cwhub
  2. // Resolve a symlink to find the hub item it points to.
  3. // This file is used only by pkg/leakybucket
  4. import (
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. )
  10. // itemKey extracts the map key of an item (i.e. author/name) from its pathname. Follows a symlink if necessary
  11. func itemKey(itemPath string) (string, error) {
  12. f, err := os.Lstat(itemPath)
  13. if err != nil {
  14. return "", fmt.Errorf("while performing lstat on %s: %w", itemPath, err)
  15. }
  16. if f.Mode()&os.ModeSymlink == 0 {
  17. // it's not a symlink, so the filename itsef should be the key
  18. return filepath.Base(itemPath), nil
  19. }
  20. // resolve the symlink to hub file
  21. pathInHub, err := os.Readlink(itemPath)
  22. if err != nil {
  23. return "", fmt.Errorf("while reading symlink of %s: %w", itemPath, err)
  24. }
  25. author := filepath.Base(filepath.Dir(pathInHub))
  26. fname := filepath.Base(pathInHub)
  27. fname = strings.TrimSuffix(fname, ".yaml")
  28. fname = strings.TrimSuffix(fname, ".yml")
  29. return fmt.Sprintf("%s/%s", author, fname), nil
  30. }
  31. // GetItemByPath retrieves the item from hubIdx based on the path. To achieve this it will resolve symlink to find associated hub item.
  32. func (h *Hub) GetItemByPath(itemType string, itemPath string) (*Item, error) {
  33. itemKey, err := itemKey(itemPath)
  34. if err != nil {
  35. return nil, err
  36. }
  37. m := h.GetItemMap(itemType)
  38. if m == nil {
  39. return nil, fmt.Errorf("item type %s doesn't exist", itemType)
  40. }
  41. v, ok := m[itemKey]
  42. if !ok {
  43. return nil, fmt.Errorf("%s not found in %s", itemKey, itemType)
  44. }
  45. return &v, nil
  46. }