summaryrefslogtreecommitdiff
path: root/lib/std/mktemp.myr
blob: f5e86611f993d0ada2797cf8ae09b4bdd0ecc30f (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
106
107
use "die"
use "alloc"
use "env"
use "errno"
use "fmt"
use "option"
use "pathjoin"
use "memops"
use "rand"
use "result"
use "sldup"
use "syswrap"
use "types"

pkg std =
	const mktemp		: (base : byte[:], opt : fdopt, mode : int64 -> std.result((fd, byte[:]), errno))
	const mktempat		: (dir : byte[:], base : byte[:], opt : fdopt, mode : int64 -> std.result((fd, byte[:]), errno))
	const mkdtemp		: (base : byte[:], mode : int64 -> std.result(byte[:], errno))
	const mkdtempat		: (dir : byte[:], base : byte[:], mode : int64 -> std.result(byte[:], errno))
	const mktemppath	: (base : byte[:] -> byte[:])
;;

const Retries = 100

const mktemp = {base, opt, mode
	var tmpdir

	match std.getenv("TMPDIR")
	| `std.Some d:	tmpdir = d
	| `std.None:	tmpdir = "/tmp"
	;;
	
	-> mktempat(tmpdir, base, opt, mode)
	
}

const mktempat = {tmpdir, base, opt, mode
	var path

	for var i = 0; i < Retries; i++
		path = randpath(tmpdir, base)
		match std.openmode(path, opt | Ocreat, mode)
		| `Err e:
			if e != Eexist
				std.slfree(path)
				-> `Err e
			;;
		| `Ok fd:
			-> `Ok (fd, path)
		;;
		std.slfree(path)
	;;
	-> `Err Eexist
}

const mkdtemp = {base, mode
	var tmpdir

	match std.getenv("TMPDIR")
	| `std.Some d:	tmpdir = d
	| `std.None:	tmpdir = "/tmp"
	;;

	-> mkdtempat(tmpdir, base, mode)
}

const mkdtempat = {tmpdir, base, mode
	var path

	for var i = 0; i < Retries; i++
		path = randpath(tmpdir, base)
		match std.mkdir(path, mode)
		| Enone:
			-> `Ok path
		| e:
			if e != Eexist
				std.slfree(path)
				-> `Err e
			;;
		;;
		std.slfree(path)
	;;
	-> `Err Eexist
}

const mktemppath = {base
	var tmpdir, path

	match std.getenv("TMPDIR")
	| `std.Some d:	tmpdir = d
	| `std.None:	tmpdir = "/tmp"
	;;

	path = randpath(tmpdir, base)
	-> path
}

const randpath = {dir, base
	var f, p
	var v : uint64

	v = std.randnum()
	f = fmt("{}{}", base, v)
	p = pathcat(dir, f)
	std.slfree(f)
	-> p
}