From f604728f9756ec03847ef6348805d5cb5f3390ef Mon Sep 17 00:00:00 2001 From: Sarat Chandra Date: Tue, 2 Jun 2020 17:10:29 +0530 Subject: [PATCH] feat: For files in the home directory, only store relative path in db This will allow restoring into home directories even if the username or home directory is different --- cmd/shelf/actions.go | 12 ++++++++++++ cmd/shelf/db.go | 18 +++++++++++++++++- cmd/shelf/utils.go | 7 ++++++- 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/cmd/shelf/actions.go b/cmd/shelf/actions.go index f7c2b4f..33d0525 100644 --- a/cmd/shelf/actions.go +++ b/cmd/shelf/actions.go @@ -261,6 +261,18 @@ func RestoreShelf(cliCtx *cli.Context) error { return err } + // If the symlink path in db is absolute, it will be put in home directory + if !path.IsAbs(lPath) { + fmt.Printf("lPath is abs: ") + home := getHomeDir() + lPath = path.Join(home, lPath) + } + + err = os.MkdirAll(path.Dir(lPath), 0755) + if err != nil { + return err + } + err = os.Symlink(path.Join(shelfPath, fName), lPath) if err != nil { if os.IsExist(err) { diff --git a/cmd/shelf/db.go b/cmd/shelf/db.go index 173dc2a..a7685dd 100644 --- a/cmd/shelf/db.go +++ b/cmd/shelf/db.go @@ -2,9 +2,11 @@ package main import ( "encoding/json" + "fmt" "io" "os" "path" + "strings" ) // DB is the db for shelf to store where each symlink is supposed to go. @@ -27,7 +29,21 @@ func (db *DB) Marshal(w io.Writer) error { // AddLink adds the file and link paths to the DB func (db *DB) AddLink(filePath, linkPath string) { - db.Links[filePath] = linkPath + // If the linkpath is in the home directory, only put absolute path from home + home := getHomeDir() + if strings.HasPrefix(linkPath, home) { + + // Strip home directory + l := strings.TrimPrefix(linkPath, home) + + // Strip any extra slashes at the prefix + l = strings.TrimPrefix(l, "/") + + fmt.Printf("linkpath: %s, home: %s\n", linkPath, home) + db.Links[filePath] = path.Clean(l) + return + } + db.Links[filePath] = path.Clean(linkPath) } // NewDB creates a shelf DB diff --git a/cmd/shelf/utils.go b/cmd/shelf/utils.go index cef434a..22df25c 100644 --- a/cmd/shelf/utils.go +++ b/cmd/shelf/utils.go @@ -38,6 +38,10 @@ func GetOrCreateShelvesDir() (string, error) { } func getShelfDirPath() string { + return path.Join(getHomeDir(), shelvesDIR) +} + +func getHomeDir() string { var ( home string ) @@ -47,7 +51,8 @@ func getShelfDirPath() string { home = os.Getenv("HOME") } } - return path.Join(home, shelvesDIR) + + return path.Clean(home) } // SOURCE: https://gist.github.com/mimoo/25fc9716e0f1353791f5908f94d6e726