~nskaggs/+junk/xenial-test

« back to all changes in this revision

Viewing changes to src/github.com/juju/govmomi/govc/importx/archive.go

  • Committer: Nicholas Skaggs
  • Date: 2016-10-24 20:56:05 UTC
  • Revision ID: nicholas.skaggs@canonical.com-20161024205605-z8lta0uvuhtxwzwl
Initi with beta15

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
Copyright (c) 2014 VMware, Inc. All Rights Reserved.
 
3
 
 
4
Licensed under the Apache License, Version 2.0 (the "License");
 
5
you may not use this file except in compliance with the License.
 
6
You may obtain a copy of the License at
 
7
 
 
8
    http://www.apache.org/licenses/LICENSE-2.0
 
9
 
 
10
Unless required by applicable law or agreed to in writing, software
 
11
distributed under the License is distributed on an "AS IS" BASIS,
 
12
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
13
See the License for the specific language governing permissions and
 
14
limitations under the License.
 
15
*/
 
16
 
 
17
package importx
 
18
 
 
19
import (
 
20
        "archive/tar"
 
21
        "io"
 
22
        "os"
 
23
        "path/filepath"
 
24
)
 
25
 
 
26
type Archive interface {
 
27
        Open(string) (io.ReadCloser, int64, error)
 
28
}
 
29
 
 
30
type TapeArchive struct {
 
31
        path string
 
32
}
 
33
 
 
34
type TapeArchiveEntry struct {
 
35
        io.Reader
 
36
        f *os.File
 
37
}
 
38
 
 
39
func (t *TapeArchiveEntry) Close() error {
 
40
        return t.f.Close()
 
41
}
 
42
 
 
43
func (t *TapeArchive) Open(name string) (io.ReadCloser, int64, error) {
 
44
        f, err := os.Open(t.path)
 
45
        if err != nil {
 
46
                return nil, 0, err
 
47
        }
 
48
 
 
49
        r := tar.NewReader(f)
 
50
 
 
51
        for {
 
52
                h, err := r.Next()
 
53
 
 
54
                if err == io.EOF {
 
55
                        break
 
56
                }
 
57
 
 
58
                matched, err := filepath.Match(name, h.Name)
 
59
                if err != nil {
 
60
                        return nil, 0, err
 
61
                }
 
62
 
 
63
                if matched {
 
64
                        return &TapeArchiveEntry{r, f}, h.Size, nil
 
65
                }
 
66
        }
 
67
 
 
68
        _ = f.Close()
 
69
 
 
70
        return nil, 0, os.ErrNotExist
 
71
}
 
72
 
 
73
type FileArchive struct {
 
74
        path string
 
75
}
 
76
 
 
77
func (t *FileArchive) Open(name string) (io.ReadCloser, int64, error) {
 
78
        fpath := name
 
79
 
 
80
        if name != t.path {
 
81
                fpath = filepath.Join(filepath.Dir(t.path), name)
 
82
        }
 
83
 
 
84
        s, err := os.Stat(fpath)
 
85
        if err != nil {
 
86
                return nil, 0, err
 
87
        }
 
88
 
 
89
        f, err := os.Open(fpath)
 
90
        if err != nil {
 
91
                return nil, 0, err
 
92
        }
 
93
 
 
94
        return f, s.Size(), nil
 
95
}