File: tarfs.go

package info (click to toggle)
golang-github-hanwen-go-fuse 0.0~git20190214.58dcd77-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,076 kB
  • sloc: cpp: 78; sh: 77; makefile: 16
file content (108 lines) | stat: -rw-r--r-- 1,911 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// Copyright 2016 the Go-FUSE Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package zipfs

import (
	"archive/tar"
	"bytes"
	"compress/bzip2"
	"compress/gzip"
	"github.com/hanwen/go-fuse/fuse"
	"io"
	"os"
	"strings"
	"syscall"
)

// TODO - handle symlinks.

func HeaderToFileInfo(out *fuse.Attr, h *tar.Header) {
	out.Mode = uint32(h.Mode)
	out.Size = uint64(h.Size)
	out.Uid = uint32(h.Uid)
	out.Gid = uint32(h.Gid)
	out.SetTimes(&h.AccessTime, &h.ModTime, &h.ChangeTime)
}

type TarFile struct {
	data []byte
	tar.Header
}

func (f *TarFile) Stat(out *fuse.Attr) {
	HeaderToFileInfo(out, &f.Header)
	out.Mode |= syscall.S_IFREG
}

func (f *TarFile) Data() []byte {
	return f.data
}

func NewTarTree(r io.Reader) map[string]MemFile {
	files := map[string]MemFile{}
	tr := tar.NewReader(r)

	var longName *string
	for {
		hdr, err := tr.Next()
		if err == io.EOF {
			// end of tar archive
			break
		}
		if err != nil {
			// handle error
		}

		if hdr.Typeflag == 'L' {
			buf := bytes.NewBuffer(make([]byte, 0, hdr.Size))
			io.Copy(buf, tr)
			s := buf.String()
			longName = &s
			continue
		}

		if longName != nil {
			hdr.Name = *longName
			longName = nil
		}

		if strings.HasSuffix(hdr.Name, "/") {
			continue
		}

		buf := bytes.NewBuffer(make([]byte, 0, hdr.Size))
		io.Copy(buf, tr)

		files[hdr.Name] = &TarFile{
			Header: *hdr,
			data:   buf.Bytes(),
		}
	}
	return files
}

func NewTarCompressedTree(name string, format string) (map[string]MemFile, error) {
	f, err := os.Open(name)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	var stream io.Reader
	switch format {
	case "gz":
		unzip, err := gzip.NewReader(f)
		if err != nil {
			return nil, err
		}
		defer unzip.Close()
		stream = unzip
	case "bz2":
		unzip := bzip2.NewReader(f)
		stream = unzip
	}

	return NewTarTree(stream), nil
}