chtimes.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package system
  2. import (
  3. "os"
  4. "syscall"
  5. "time"
  6. "unsafe"
  7. )
  8. var (
  9. maxTime time.Time
  10. )
  11. func init() {
  12. if unsafe.Sizeof(syscall.Timespec{}.Nsec) == 8 {
  13. // This is a 64 bit timespec
  14. // os.Chtimes limits time to the following
  15. maxTime = time.Unix(0, 1<<63-1)
  16. } else {
  17. // This is a 32 bit timespec
  18. maxTime = time.Unix(1<<31-1, 0)
  19. }
  20. }
  21. // Chtimes changes the access time and modified time of a file at the given path
  22. func Chtimes(name string, atime time.Time, mtime time.Time) error {
  23. unixMinTime := time.Unix(0, 0)
  24. unixMaxTime := maxTime
  25. // If the modified time is prior to the Unix Epoch, or after the
  26. // end of Unix Time, os.Chtimes has undefined behavior
  27. // default to Unix Epoch in this case, just in case
  28. if atime.Before(unixMinTime) || atime.After(unixMaxTime) {
  29. atime = unixMinTime
  30. }
  31. if mtime.Before(unixMinTime) || mtime.After(unixMaxTime) {
  32. mtime = unixMinTime
  33. }
  34. if err := os.Chtimes(name, atime, mtime); err != nil {
  35. return err
  36. }
  37. // Take platform specific action for setting create time.
  38. if err := setCTime(name, mtime); err != nil {
  39. return err
  40. }
  41. return nil
  42. }