From 3e5bcb3d970d449119840039474f4de0437981af Mon Sep 17 00:00:00 2001
From: Lufty <lufty.abdillah@gmail.com>
Date: Fri, 18 Jun 2021 22:03:52 +0700
Subject: [PATCH] Fixed directory mapping

Added also symlink file handling
Trim separator prefix and suffix from passed path


Dirpath to be created should be using vmpath
---
 fs/manifest.go  |  2 ++
 lepton/image.go | 22 +++++++++-------------
 2 files changed, 11 insertions(+), 13 deletions(-)

diff --git a/fs/manifest.go b/fs/manifest.go
index f1fd1434..e6469ad0 100644
--- a/fs/manifest.go
+++ b/fs/manifest.go
@@ -509,6 +509,8 @@ func (m *Manifest) MkdirPath(path string) {
 }
 
 func mkDirPath(parent map[string]interface{}, path string) map[string]interface{} {
+	path = strings.TrimPrefix(path, "/")
+	path = strings.TrimSuffix(path, "/")
 	parts := strings.Split(path, "/")
 	for _, element := range parts {
 		parent = mkDir(parent, element)
diff --git a/lepton/image.go b/lepton/image.go
index d2abb005..443b3da7 100644
--- a/lepton/image.go
+++ b/lepton/image.go
@@ -355,7 +355,6 @@ func BuildManifest(c *types.Config) (*fs.Manifest, error) {
 
 func addMappedFiles(src string, dest string, workDir string, m *fs.Manifest) error {
 	dir, pattern := filepath.Split(src)
-	parentDir := filepath.Base(dir)
 	err := filepath.Walk(dir, func(hostpath string, info os.FileInfo, err error) error {
 		if err != nil {
 			return err
@@ -364,24 +363,21 @@ func addMappedFiles(src string, dest string, workDir string, m *fs.Manifest) err
 		hostdir, filename := filepath.Split(hostpath)
 		matched, _ := filepath.Match(pattern, filename)
 		if matched {
-			if info.IsDir() {
-				addedDir := parentDir
-				hostBase := filepath.Base(hostpath)
-				if hostBase != parentDir {
-					filepath.Join(parentDir, hostBase)
-				}
-				return m.AddDirectory(addedDir, workDir)
-			}
-
 			reldir, err := filepath.Rel(dir, hostdir)
 			if err != nil {
 				return err
 			}
 			vmpath := filepath.Join(dest, reldir, filename)
-			err = m.AddFile(vmpath, hostpath)
-			if err != nil {
-				return err
+
+			if info.IsDir() {
+				m.MkdirPath(vmpath)
+				return nil
+			}
+
+			if (info.Mode() & os.ModeSymlink) == os.ModeSymlink {
+				return m.AddLink(vmpath, hostpath)
 			}
+			return m.AddFile(vmpath, hostpath)
 		}
 		return nil
 	})