simple program for visiting other townies' home directories
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
1.6 KiB

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math/rand"
  6. "os"
  7. "os/exec"
  8. "time"
  9. "github.com/AlecAivazis/survey/v2"
  10. )
  11. func main() {
  12. var err error
  13. if len(os.Args) > 2 {
  14. fmt.Println("expected zero or one arguments")
  15. }
  16. if len(os.Args) > 1 {
  17. arg := os.Args[1]
  18. switch arg {
  19. case "-r", "--random":
  20. err = visitRandomUser()
  21. default:
  22. err = visitUsername(os.Args[1])
  23. }
  24. } else {
  25. err = visitPrompt()
  26. }
  27. if err != nil {
  28. fmt.Fprintf(os.Stderr, "%s\n", err)
  29. os.Exit(1)
  30. }
  31. }
  32. func visitRandomUser() error {
  33. rand.Seed(time.Now().UnixNano())
  34. usernames, err := getUsernames()
  35. if err != nil {
  36. return err
  37. }
  38. return visitUser(usernames[rand.Intn(len(usernames))])
  39. }
  40. func visitUsername(username string) error {
  41. usernames, err := getUsernames()
  42. if err != nil {
  43. return err
  44. }
  45. for _, name := range usernames {
  46. if name == username {
  47. return visitUser(username)
  48. }
  49. }
  50. return fmt.Errorf("no such user: %s", username)
  51. }
  52. func visitPrompt() error {
  53. usernames, err := getUsernames()
  54. if err != nil {
  55. return err
  56. }
  57. username := ""
  58. prompt := &survey.Select{
  59. Message: "Choose a townie to visit!",
  60. Options: usernames,
  61. }
  62. survey.AskOne(prompt, &username)
  63. return visitUser(username)
  64. }
  65. func visitUser(username string) error {
  66. fmt.Println("TODO visit", username)
  67. return nil
  68. }
  69. func getUsernames() ([]string, error) {
  70. cmd := exec.Command("/bin/bash", "-c", "town stats | jq -r '.users|map(.username)'")
  71. output, err := cmd.Output()
  72. if err != nil {
  73. return nil, err
  74. }
  75. usernames := []string{}
  76. err = json.Unmarshal(output, &usernames)
  77. if err != nil {
  78. return nil, err
  79. }
  80. return usernames, nil
  81. }