history.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package config
  2. import (
  3. "os"
  4. "path/filepath"
  5. "github.com/0xJacky/Nginx-UI/internal/helper"
  6. "github.com/0xJacky/Nginx-UI/internal/nginx"
  7. "github.com/0xJacky/Nginx-UI/model"
  8. "github.com/0xJacky/Nginx-UI/query"
  9. "github.com/uozi-tech/cosy/logger"
  10. )
  11. // CheckAndCreateHistory compares the provided content with the current content of the file
  12. // at the specified path and creates a history record if they are different.
  13. // The path must be under nginx.GetConfPath().
  14. func CheckAndCreateHistory(path string, content string) error {
  15. // Check if path is under nginx.GetConfPath()
  16. if !helper.IsUnderDirectory(path, nginx.GetConfPath()) {
  17. return ErrPathIsNotUnderTheNginxConfDir
  18. }
  19. // Read the current content of the file
  20. currentContent, err := os.ReadFile(path)
  21. if err != nil {
  22. return nil
  23. }
  24. // Compare the contents
  25. if string(currentContent) == content {
  26. // Contents are identical, no need to create history
  27. return nil
  28. }
  29. // Contents are different, create a history record (config backup)
  30. backup := &model.ConfigBackup{
  31. Name: filepath.Base(path),
  32. FilePath: path,
  33. Content: string(currentContent),
  34. }
  35. // Save the backup to the database
  36. cb := query.ConfigBackup
  37. err = cb.Create(backup)
  38. if err != nil {
  39. logger.Error("Failed to create config backup:", err)
  40. return err
  41. }
  42. return nil
  43. }