Skip to content

Instantly share code, notes, and snippets.

@billmetangmo
Created April 30, 2018 11:17
Show Gist options
  • Save billmetangmo/3fdcd1215511f510bcc4b13441ee821d to your computer and use it in GitHub Desktop.
Save billmetangmo/3fdcd1215511f510bcc4b13441ee821d to your computer and use it in GitHub Desktop.
Extract files from a zip that was zipped without directories but just files even if files are inside directories
// Iterate through all the zip files in multi-part form-data (memory or disk)
// For each file, extract it to destDir and change permissions of the file to the user one
// If the zip file is a directory , empty subdirectories are ignored
func extractFilesWithUserRights(files []*zip.File, filePath string, username string) error {
uid, gid, err := getIdentifier(username)
if err != nil {
return err
}
for _, f := range files {
// Get relative path because if zip archive is a directory: f.Name is prefixed this dir name
// relpath is the path of the file inside the zip (by removing prefix)
// See api/client/http_client.go:112
relpath := strings.Join(strings.SplitAfter(f.Name, "/")[1:], "")
// If empty, f.Name is at the root of the zip archive
// we just have to write it in experiment basepath
if relpath == "" {
fpath := filepath.Join(filePath, f.Name)
extractFile(f, fpath)
if err != nil {
return err
}
err = os.Chown(fpath, uid, gid)
if err != nil {
return err
}
continue
}
// If not, f.Name contains at least one dir in its filename
// filepath.Split split relpath in dir(s)+file
// dPath is the directory part we need to create inside experiment basepth
dir, _ := filepath.Split(relpath)
dPath := filepath.Join(filePath, dir)
fpath := filepath.Join(filePath, relpath)
if dPath != "" {
if err := os.MkdirAll(dPath, f.Mode()|0700); err != nil {
return err
}
if err := os.Chown(dPath, uid, gid); err != nil {
return err
}
}
// Then we copy the file at experiment basepath/relativepath
extractFile(f, fpath)
if err != nil {
return err
}
err = os.Chown(fpath, uid, gid)
if err != nil {
return err
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment