File: add_file_test.go

package info (click to toggle)
golang-github-mitchellh-go-fs 0.0~git20161108.7bae45d-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 160 kB
  • sloc: makefile: 2
file content (102 lines) | stat: -rw-r--r-- 2,203 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
98
99
100
101
102
package fat

import (
	"github.com/mitchellh/go-fs"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestAddFile(t *testing.T) {
	// Create a temporary file to be our floppy drive
	floppyF, err := ioutil.TempFile("", "go-fs")
	if err != nil {
		t.Fatalf("Error creating temporary file for floppy: %s", err)
	}
	defer floppyF.Close()
	// defer os.Remove(floppyF.Name())

	// Set the size of the file to be a floppy sized
	if err := floppyF.Truncate(1440 * 1024); err != nil {
		t.Fatalf("Error creating floppy: %s", err)
	}

	// BlockDevice backed by the file for our filesystem
	device, err := fs.NewFileDisk(floppyF)
	if err != nil {
		t.Fatalf("Error creating floppy: %s", err)
	}

	// Format the block device so it contains a valid FAT filesystem
	formatConfig := &SuperFloppyConfig{
		FATType: FAT12,
		Label:   "go-fs",
		OEMName: "go-fs",
	}
	if FormatSuperFloppy(device, formatConfig); err != nil {
		t.Fatalf("Error creating floppy: %s", err)
	}

	// The actual FAT filesystem
	fatFs, err := New(device)
	if err != nil {
		t.Fatalf("Error creating floppy: %s", err)
	}

	// Get the root directory to the filesystem
	rootDir, err := fatFs.RootDir()
	if err != nil {
		t.Fatalf("Error creating floppy: %s", err)
	}

	var filenames [128]string

	// Go over each file and copy it.
	for i := 0; i < 128; i++ {
		filenames[i] = strings.Repeat("A", i+1) + ".EXT"
	}

	for _, filename := range filenames {
		if addSingleFile(rootDir, filename); err != nil {
			t.Fatalf("Error adding file to floppy: %s", err)
		}
	}

	entries := rootDir.Entries()

	for i, entry := range entries {
		expecting := filenames[i]
		if entry.Name() != expecting {
			// Name() returns the short name, how do we get the long name?
			// t.Fatalf("Excepting %s, found %s", expecting, entry.Name())
		}
	}
}

func addSingleFile(dir fs.Directory, src string) error {
	inputF, err := os.Create(src)
	if err != nil {
		return err
	}
	defer inputF.Close()
	defer os.Remove(src)

	entry, err := dir.AddFile(filepath.Base(src))
	if err != nil {
		return err
	}

	fatFile, err := entry.File()
	if err != nil {
		return err
	}

	if _, err := io.Copy(fatFile, inputF); err != nil {
		return err
	}

	return nil
}