code that works

This commit is contained in:
Lilian Jónsdóttir 2024-03-11 17:23:36 -07:00
parent 8de3930a00
commit 746899a2c3
12 changed files with 812 additions and 0 deletions

47
pkg/tmpfile/tmpfile.go Normal file
View file

@ -0,0 +1,47 @@
package tmpfile
import (
"math/rand"
"os"
"strings"
"git.burning.moe/celediel/agedit/pkg/env"
)
const chars string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
type Generator struct {
Prefix, Suffix string
Length int
}
// GenerateName generates a random temporary filename like agedit_geef0XYC30RGV
func (g *Generator) GenerateName() string {
return g.Prefix + randomString(chars, g.Length) + g.Suffix
}
// GenerateFullPath generates a random temporary filename and appends it to the OS's temporary directory
func (g *Generator) GenerateFullPath() string {
return env.GetTempDirectory() + string(os.PathSeparator) + g.GenerateName()
}
// NewGenerator returns a new Generator
func NewGenerator(prefix, suffix string, length int) Generator {
return Generator{
Prefix: prefix,
Suffix: suffix,
Length: length,
}
}
func randomString(set string, length int) string {
out := strings.Builder{}
for i := 0; i < length; i++ {
out.WriteByte(randomChar(set))
}
return out.String()
}
func randomChar(set string) byte {
return set[rand.Intn(len(set))]
}

View file

@ -0,0 +1,43 @@
package tmpfile
import (
"io/fs"
"os"
"testing"
)
var generator = NewGenerator("test_", ".txt", 18)
// TestCanCreateTmpFile tests if temporary files can be created and removed successfully
func TestCanCreateTmpFile(t *testing.T) {
b := []byte{104, 101, 108, 108, 111, 32, 116, 104, 101, 114, 101}
for range 1000 {
outfile := generator.GenerateFullPath()
err := os.WriteFile(outfile, b, fs.FileMode(0600))
if err != nil {
t.Fatal(err)
}
if _, err = os.Stat(outfile); err != nil && os.IsNotExist(err) {
t.Fatal(err)
}
if err = os.Remove(outfile); err != nil {
t.Fatal(err)
}
}
}
// TestUniqueTmpFile generates a large number of random names to make sure they're all unique
func TestUniqueTmpFile(t *testing.T) {
var generated_names = map[string]string{}
for range 100000 {
name := generator.GenerateName()
if val, ok := generated_names[name]; ok {
t.Fatal("Non unique name", val)
}
generated_names[name] = name
}
}