From 8149e5151ba4372ee23c83b34569276ae755356f Mon Sep 17 00:00:00 2001 From: barnettZQG Date: Wed, 4 Jul 2018 11:39:08 +0800 Subject: [PATCH] [REV] zip support uid and gid --- util/comman.go | 20 ++++++++++++++++---- util/comman_test.go | 4 ++-- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/util/comman.go b/util/comman.go index 397e6fb87..c348cf3b5 100644 --- a/util/comman.go +++ b/util/comman.go @@ -28,6 +28,7 @@ import ( "os/exec" "path" "path/filepath" + "reflect" "strconv" "strings" "sync" @@ -403,22 +404,23 @@ func Zip(source, target string) error { if err != nil { return err } - header, err := zip.FileInfoHeader(info) if err != nil { return err } - if baseDir != "" { header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source)) } - if info.IsDir() { header.Name += "/" } else { header.Method = zip.Deflate } - + //set file uid and + elem := reflect.ValueOf(info.Sys()).Elem() + uid := elem.FieldByName("Uid").Uint() + gid := elem.FieldByName("Gid").Uint() + header.Comment = fmt.Sprintf("%d/%d", uid, gid) writer, err := archive.CreateHeader(header) if err != nil { return err @@ -474,6 +476,16 @@ func Unzip(archive, target string) error { if _, err := io.Copy(targetFile, fileReader); err != nil { return err } + if file.Comment != "" && strings.Contains(file.Comment, "/") { + guid := strings.Split(file.Comment, "/") + if len(guid) == 2 { + uid, _ := strconv.Atoi(guid[0]) + gid, _ := strconv.Atoi(guid[1]) + if err := os.Chown(path, uid, gid); err != nil { + return err + } + } + } return nil } if err := run(); err != nil { diff --git a/util/comman_test.go b/util/comman_test.go index 688aadc75..1d50b5245 100644 --- a/util/comman_test.go +++ b/util/comman_test.go @@ -51,13 +51,13 @@ func TestGetDirSizeByCmd(t *testing.T) { } func TestZip(t *testing.T) { - if err := Zip("/tmp/test/", "/tmp/test.zip"); err != nil { + if err := Zip("/tmp/cache", "/tmp/cache.zip"); err != nil { t.Fatal(err) } } func TestUnzip(t *testing.T) { - if err := Unzip("/tmp/test.aaa.zip", "/tmp/rainbond"); err != nil { + if err := Unzip("/tmp/cache.zip", "/tmp/cache0"); err != nil { t.Fatal(err) } }