Skip to content

archive/tar: AddFS fails to include empty directories #69459

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
purpleidea opened this issue Sep 13, 2024 · 2 comments
Closed

archive/tar: AddFS fails to include empty directories #69459

purpleidea opened this issue Sep 13, 2024 · 2 comments

Comments

@purpleidea
Copy link

Go version

1.23

Output of go env in your module/workspace:

N/A

What did you do?

Created a tar file that should have included empty directories.

What did you see happen?

No empty directories were included.

What did you expect to see?

I'm using the archive/tar package and the AddFS function: https://pkg.go.dev/archive/tar#Writer.AddFS

This is very useful thanks!

I noticed a bug: it's skipping over empty directories in the output tar file! (Tar archives are not git directories and this is not expected.)

I've looked at the source for the AddFS function and I've created a fixed version which correctly adds those directories. It's shown here as a standalone function. You can transplant the body over to the function.

Cheers!

func addFS(tw *tar.Writer, fsys fs.FS) error {
	return fs.WalkDir(fsys, ".", func(name string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		info, err := d.Info()
		if err != nil {
			return err
		}
		// TODO(#49580): Handle symlinks when fs.ReadLinkFS is available.
		if !info.Mode().IsRegular() && !info.Mode().IsDir() {
			return fmt.Errorf("tar: cannot add non-regular file")
		}
		h, err := tar.FileInfoHeader(info, "")
		if err != nil {
			return err
		}
		h.Name = name

		if d.IsDir() {
			h.Name += "/" // dir
			fmt.Printf("XXX: DIR: %+v\n", h.Name)
		}

		if err := tw.WriteHeader(h); err != nil {
			return err
		}

		if d.IsDir() {
			return nil // no contents to copy in
		}

		f, err := fsys.Open(name)
		if err != nil {
			return err
		}
		defer f.Close()
		_, err = io.Copy(tw, f)
		return err
	})
}
@gabyhelp
Copy link

Related Issues and Documentation

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)

@seankhliao
Copy link
Member

Duplicate of #66831

@seankhliao seankhliao marked this as a duplicate of #66831 Sep 13, 2024
@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Sep 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants