aboutsummaryrefslogtreecommitdiffstats
path: root/worker/mbox/create.go
blob: 7c4d9f7bc28b6794deb8ce05a6afacc3062df556 (plain) (blame)
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
package mboxer

import (
	"io"
	"os"
	"path/filepath"
	"strings"
)

func createMailboxContainer(path string) (*mailboxContainer, error) {

	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}

	defer file.Close()

	fileInfo, err := file.Stat()
	if err != nil {
		return nil, err
	}

	mbdata := &mailboxContainer{mailboxes: make(map[string]*container)}

	openMboxFile := func(path string, r io.Reader) error {
		// read mbox file
		messages, err := Read(r)
		if err != nil {
			return err
		}
		_, name := filepath.Split(path)
		name = strings.TrimSuffix(name, ".mbox")
		mbdata.mailboxes[name] = &container{filename: path, messages: messages}
		return nil
	}

	if fileInfo.IsDir() {
		files, err := filepath.Glob(filepath.Join(path, "*.mbox"))
		if err != nil {
			return nil, err
		}
		for _, file := range files {
			f, err := os.Open(file)
			if err != nil {
				continue
			}
			if err := openMboxFile(file, f); err != nil {
				return nil, err
			}
			f.Close()
		}
	} else {
		if err := openMboxFile(path, file); err != nil {
			return nil, err
		}
	}

	return mbdata, nil
}