Skip to content

Commit

Permalink
Merge pull request #118 from x-motemen/refine-mtime
Browse files Browse the repository at this point in the history
use git log to determine when a file was last updated
  • Loading branch information
Songmu authored Oct 28, 2023
2 parents 9ee9694 + 4d666b8 commit 7880ee2
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 9 deletions.
7 changes: 1 addition & 6 deletions broker.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"net/http"
"os"
"path/filepath"
"time"

"github.com/motemen/go-wsse"
"github.com/x-motemen/blogsync/atom"
Expand Down Expand Up @@ -86,11 +85,7 @@ func (b *broker) LocalPath(e *entry) string {
}

func (b *broker) StoreFresh(e *entry, path string) (bool, error) {
var localLastModified time.Time
if fi, err := os.Stat(path); err == nil {
localLastModified = fi.ModTime()
}

localLastModified, _ := modTime(path)
if e.LastModified.After(localLastModified) {
logf("fresh", "remote=%s > local=%s", e.LastModified, localLastModified)
if err := b.Store(e, path, ""); err != nil {
Expand Down
51 changes: 48 additions & 3 deletions entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import (
"log"
"net/url"
"os"
"os/exec"
"regexp"
"runtime"
"strings"
"sync"
"time"

"github.com/x-motemen/blogsync/atom"
Expand Down Expand Up @@ -213,12 +215,11 @@ func entryFromReader(source io.Reader) (*entry, error) {
t := time.Now()
entry.LastModified = &t
} else {
fi, err := os.Stat(f.Name())
ti, err := modTime(f.Name())
if err != nil {
return nil, err
}
t := fi.ModTime()
entry.LastModified = &t
entry.LastModified = &ti
}
}

Expand All @@ -232,3 +233,47 @@ func asEntry(atomEntry *atom.Entry, err error) (*entry, error) {

return entryFromAtom(atomEntry)
}

var getGit = sync.OnceValue(func() string {
g, err := exec.LookPath("git")
if err != nil {
return ""
}
return g
})

func doCommand(name string, args ...string) (string, error) {
cmd := exec.Command(name, args...)
cmd.Stderr = os.Stderr
bb, err := cmd.Output()
if err != nil {
return "", err
}
return strings.TrimSpace(string(bb)), nil
}

func modTime(fpath string) (time.Time, error) {
fi, err := os.Stat(fpath)
if err != nil {
return time.Time{}, err
}
ti := fi.ModTime()

if git := getGit(); git != "" {
// ref. https://git-scm.com/docs/pretty-formats#Documentation/pretty-formats.txt-emaiem
// %aI means "author date, strict ISO 8601 format"
timeStr, err := doCommand(git, "log", "-1", "--format=%aI", "--", fpath)
if err == nil && timeStr != "" {
// check if the file is clean (not modified) on git
out, err := doCommand(git, "status", "-s", "--", fpath)
// if the output is empty, it means the file has not been modified
if err == nil && out == "" {
t, err := time.Parse(time.RFC3339, timeStr)
if err == nil {
ti = t
}
}
}
}
return ti, nil
}

0 comments on commit 7880ee2

Please sign in to comment.