I want to get the date when a folder was renamed, from terminal it can be done using the stat
command, e.g.:
> stat -x folders/folder1
File: "folders/folder1"
Size: 64 FileType: Directory
Mode: (0755/drwxr-xr-x) Uid: (2006390509/username) Gid:
(296108113/EMEA\Domain Users)
Device: 1,4 Inode: 2599274 Links: 2
Access: Mon Nov 12 17:59:57 2018
Modify: Mon Nov 12 14:12:20 2018
Change: Mon Nov 12 17:28:01 2018
The change date is the last date the folder's metadata was changed, which includes renaming.
Is there any way to get it with Go without using os.exec
and parsing the output? os.Stat
seems to provide only the last modification date which doesn't change when the folder is renamed.
Change time is not accessible in os.FileInfo
but can be get via os.FileInfo.Sys()
which stores that data.
You can get it by
package main
import (
"fmt"
"log"
"os"
"syscall"
"time"
)
func main() {
f, err := os.Stat("your/dir")
if err != nil {
log.Fatalf("err reading: %v", err)
}
//access change time saved in os.FileInfo.Sys()
changeTime := f.Sys().(*syscall.Stat_t).Ctim
fmt.Print(time.Unix(changeTime.Unix()).String())
}
Ofcourse you need to check if f.Sys()
it's proper type, but yeah syscall.Stat_t.Ctim
is probably what you wanted.
If you're happy with calling os.Exec maybe you don't mind cross-platform issues. There was some discussion about this on a github issue a while back.
This code works for me to get the changed time anyway. Not sure how/if it'll work on Windows:
file, err := os.Open("test")
if err != nil {
panic(err)
}
stat, err := file.Stat()
sys := stat.Sys().(*syscall.Stat_t)
changedTime := time.Unix(sys.Ctim.Unix())
fmt.Println(stat.ModTime())
fmt.Println(changedTime)
When I run
mv test test1 && mv test1 test && go run main.go
It gives me:
2018-11-12 17:31:38.659095951 +0000 GMT
2018-11-12 17:57:43.042208583 +0000 GMT
Which seems to correctly reflect the time I changed the dirname, and not the creation time (as in the first date)