"Fossies" - the Fresh Open Source Software Archive

Member "gdrive-2.1.1/compare.go" (28 May 2021, 1709 Bytes) of package /linux/misc/old/gdrive-2.1.1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Go source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

    1 package main
    2 
    3 import (
    4     "encoding/json"
    5     "github.com/prasmussen/gdrive/drive"
    6     "os"
    7 )
    8 
    9 const MinCacheFileSize = 5 * 1024 * 1024
   10 
   11 type Md5Comparer struct{}
   12 
   13 func (self Md5Comparer) Changed(local *drive.LocalFile, remote *drive.RemoteFile) bool {
   14     return remote.Md5() != md5sum(local.AbsPath())
   15 }
   16 
   17 type CachedFileInfo struct {
   18     Size     int64  `json:"size"`
   19     Modified int64  `json:"modified"`
   20     Md5      string `json:"md5"`
   21 }
   22 
   23 func NewCachedMd5Comparer(path string) CachedMd5Comparer {
   24     cache := map[string]*CachedFileInfo{}
   25 
   26     f, err := os.Open(path)
   27     if err == nil {
   28         json.NewDecoder(f).Decode(&cache)
   29     }
   30     f.Close()
   31     return CachedMd5Comparer{path, cache}
   32 }
   33 
   34 type CachedMd5Comparer struct {
   35     path  string
   36     cache map[string]*CachedFileInfo
   37 }
   38 
   39 func (self CachedMd5Comparer) Changed(local *drive.LocalFile, remote *drive.RemoteFile) bool {
   40     return remote.Md5() != self.md5(local)
   41 }
   42 
   43 func (self CachedMd5Comparer) md5(local *drive.LocalFile) string {
   44     // See if file exist in cache
   45     cached, found := self.cache[local.AbsPath()]
   46 
   47     // If found and modification time and size has not changed, return cached md5
   48     if found && local.Modified().UnixNano() == cached.Modified && local.Size() == cached.Size {
   49         return cached.Md5
   50     }
   51 
   52     // Calculate new md5 sum
   53     md5 := md5sum(local.AbsPath())
   54 
   55     // Cache file info if file meets size criteria
   56     if local.Size() > MinCacheFileSize {
   57         self.cacheAdd(local, md5)
   58         self.persist()
   59     }
   60 
   61     return md5
   62 }
   63 
   64 func (self CachedMd5Comparer) cacheAdd(lf *drive.LocalFile, md5 string) {
   65     self.cache[lf.AbsPath()] = &CachedFileInfo{
   66         Size:     lf.Size(),
   67         Modified: lf.Modified().UnixNano(),
   68         Md5:      md5,
   69     }
   70 }
   71 
   72 func (self CachedMd5Comparer) persist() {
   73     writeJson(self.path, self.cache)
   74 }