Skip to content
This repository has been archived by the owner on Nov 19, 2024. It is now read-only.

Updated tar archiver to create directories similar to zip archiver #83

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions tar.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io"
"os"
"path"
"path/filepath"
"strconv"
"strings"
Expand Down Expand Up @@ -135,18 +136,22 @@ func tarFile(tarWriter *tar.Writer, source, dest string) error {
baseDir = filepath.Base(source)
}

return filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
return filepath.Walk(source, func(fpath string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("error walking to %s: %v", path, err)
return fmt.Errorf("error walking to %s: %v", fpath, err)
}

header, err := tar.FileInfoHeader(info, path)
header, err := tar.FileInfoHeader(info, fpath)
if err != nil {
return fmt.Errorf("%s: making header: %v", path, err)
return fmt.Errorf("%s: making header: %v", fpath, err)
}

if baseDir != "" {
header.Name = filepath.ToSlash(filepath.Join(baseDir, strings.TrimPrefix(path, source)))
name, err := filepath.Rel(source, fpath)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any chance you can add a test for this here, that fails without this diff, and passes with this diff?

if err != nil {
return err
}
header.Name = path.Join(baseDir, filepath.ToSlash(name))
}

if header.Name == dest {
Expand All @@ -160,23 +165,23 @@ func tarFile(tarWriter *tar.Writer, source, dest string) error {

err = tarWriter.WriteHeader(header)
if err != nil {
return fmt.Errorf("%s: writing header: %v", path, err)
return fmt.Errorf("%s: writing header: %v", fpath, err)
}

if info.IsDir() {
return nil
}

if header.Typeflag == tar.TypeReg {
file, err := os.Open(path)
file, err := os.Open(fpath)
if err != nil {
return fmt.Errorf("%s: open: %v", path, err)
return fmt.Errorf("%s: open: %v", fpath, err)
}
defer file.Close()

_, err = io.CopyN(tarWriter, file, info.Size())
if err != nil && err != io.EOF {
return fmt.Errorf("%s: copying contents: %v", path, err)
return fmt.Errorf("%s: copying contents: %v", fpath, err)
}
}
return nil
Expand Down