aboutsummaryrefslogtreecommitdiff
path: root/repo.go
blob: 17ad8f3af2b3f0ca70ef1c3c898c7ba27f88b14a (plain)
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
package main

import (
	"fmt"
	"io"
	"io/fs"
	"log"
	"os"
	"path"
	"path/filepath"
)

const (
	chunkSize = 8 << 10
)

type File struct {
	Path string
	Size int64
}

func ListFiles(path string, files chan<- File) {
	err := filepath.Walk(path,
		func(p string, i fs.FileInfo, err error) error {
			if err != nil {
				log.Println(err)
				return err
			}
			if i.IsDir() {
				return nil
			}
			var file = File{p, i.Size()}
			files <- file
			return nil
		})
	if err != nil {
		log.Println(err)
	}
	close(files)
}

func ReadFiles(files <-chan File, chunks chan<- []byte) {
	var buff []byte
	var prev, read = chunkSize, 0

	for f := range files {
		file, err := os.Open(f.Path)
		if err != nil {
			log.Println(err)
			continue
		}
		for err != io.EOF {
			if prev == chunkSize {
				buff = make([]byte, chunkSize)
				prev, err = file.Read(buff)
			} else {
				read, err = file.Read(buff[prev:])
				prev += read
			}
			if err != nil && err != io.EOF {
				log.Println(err)
			}
			if prev == chunkSize {
				chunks <- buff
			}
		}
	}
	chunks <- buff
	close(chunks)
}

func PrintChunks(chunks <-chan []byte) {
	for c := range chunks {
		fmt.Println(c)
	}
}

func StoreChunks(dest string, chunks <-chan []byte) {
	i := 0
	for c := range chunks {
		path := path.Join(dest, fmt.Sprintf("%015d", i))
		os.WriteFile(path, c, 0664)
		i++
	}
}

func LoadChunks(repo string, chunks chan<- []byte) {
	err := filepath.WalkDir(repo,
		func(p string, e fs.DirEntry, err error) error {
			if err != nil {
				log.Println(err)
				return err
			}
			if e.IsDir() {
				return nil
			}
			buff, err := os.ReadFile(p)
			chunks <- buff
			return nil
		})
	if err != nil {
		log.Println(err)
	}
	close(chunks)
}