File: archive_unix.go

package info (click to toggle)
golang-github-keltia-archive 0.9.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 184 kB
  • sloc: makefile: 21
file content (97 lines) | stat: -rw-r--r-- 1,881 bytes parent folder | download
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
//go:build unix || !windows
// +build unix !windows

package archive

import (
	"bytes"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	"github.com/pkg/errors"
	"github.com/proglottis/gpgme"
)

// ------------------- GPG

// Decrypter is the gpgme interface
type Decrypter interface {
	Decrypt(r io.Reader) (*gpgme.Data, error)
}

// Gpgme is for real gpgme stuff
type Gpgme struct{}

// Decrypt does the obvious
func (Gpgme) Decrypt(r io.Reader) (*gpgme.Data, error) {
	return gpgme.Decrypt(r)
}

// NullGPG is for testing
type NullGPG struct{}

// Decrypt does the obvious
func (NullGPG) Decrypt(r io.Reader) (*gpgme.Data, error) {
	b, _ := ioutil.ReadAll(r)
	return gpgme.NewDataBytes(b)
}

// Gpg is how we use/mock decryption stuff
type Gpg struct {
	fn  string
	unc string
	gpg Decrypter
}

// NewGpgfile initializes the struct and check filename
func NewGpgfile(fn string) (*Gpg, error) {
	// Strip .gpg or .asc from filename
	base := filepath.Base(fn)
	pc := strings.Split(base, ".")
	unc := strings.Join(pc[0:len(pc)-1], ".")

	return &Gpg{fn: fn, unc: unc, gpg: Gpgme{}}, nil
}

// Extract binds it to the Archiver interface
func (a Gpg) Extract(t string) ([]byte, error) {
	// Carefully open the box
	fh, err := os.Open(a.fn)
	if err != nil {
		return []byte{}, errors.Wrap(err, "extract/open")
	}
	defer fh.Close()

	var buf bytes.Buffer

	// Do the decryption thing
	plain, err := a.gpg.Decrypt(fh)
	if err != nil {
		return []byte{}, errors.Wrap(err, "extract/decrypt")
	}
	defer plain.Close()

	// Save "plain" text

	verbose("Decrypting %s", a.fn)

	_, err = io.Copy(&buf, plain)
	if err != nil {
		return []byte{}, errors.Wrap(err, "extract/copy")
	}

	return buf.Bytes(), err
}

// Close is part of the Closer interface
func (a Gpg) Close() error {
	return nil
}

// Type returns the archive type obviously.
func (a *Gpg) Type() int {
	return ArchiveGpg
}