Skip to content

Commit

Permalink
Add remotePathFinder
Browse files Browse the repository at this point in the history
  • Loading branch information
prasmussen committed Feb 21, 2016
1 parent 0b0c7a4 commit a02adf6
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions drive/path.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package drive

import (
"fmt"
"path/filepath"
"google.golang.org/api/drive/v3"
)

func (self *Drive) newPathfinder() *remotePathfinder {
return &remotePathfinder{
service: self.service.Files,
files: make(map[string]*drive.File),
}
}

type remotePathfinder struct {
service *drive.FilesService
files map[string]*drive.File
}

func (self *remotePathfinder) absPath(f *drive.File) (string, error) {
name := f.Name

if len(f.Parents) == 0 {
return name, nil
}

var path []string

for {
parent, err := self.getParent(f.Parents[0])
if err != nil {
return "", err
}

// Stop when we find the root dir
if len(parent.Parents) == 0 {
break
}

path = append([]string{parent.Name}, path...)
f = parent
}

path = append(path, name)
return filepath.Join(path...), nil
}

func (self *remotePathfinder) getParent(id string) (*drive.File, error) {
// Check cache
if f, ok := self.files[id]; ok {
return f, nil
}

// Fetch file from drive
f, err := self.service.Get(id).Fields("id", "name", "parents").Do()
if err != nil {
return nil, fmt.Errorf("Failed to get file: %s", err)
}

// Save in cache
self.files[f.Id] = f

return f, nil
}

0 comments on commit a02adf6

Please sign in to comment.