summaryrefslogtreecommitdiff
path: root/lib/inifile/write.myr
blob: 8dc55dd7b8e2706a74d88611fb64717c45198eb9 (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
use std
use bio

use "types"

pkg inifile =
	const write	: (ini : inifile#, path : byte[:]	-> bool)
	const writef	: (ini : inifile#, fd : std.fd	-> bool)
;;

const write = {ini, path
	var ret

	match bio.create(path, bio.Wr, 0o666)
	| `std.Err e:	-> false
	| `std.Ok f:
		ret = writeini(f, ini)
		bio.close(f)
	;;
	-> ret
}

const writef = {ini, fd
	var f, ret

	f = bio.mkfile(fd, bio.Wr)
	ret = writeini(f, ini)
	bio.close(f)
	-> ret
}


const writeini = {f, ini
	var oldsect, val
	var keys

	keys = std.htkeys(ini.elts)
	std.sort(keys, {a, b
		var sa, sb

		(sa, _) = a
		(sb, _) = b
		-> std.strcmp(sa, sb)
	})

	oldsect = ""
	for (sect, key) : keys
		std.put("sect={}, oldsect={}\n", sect, oldsect)
		if !std.eq(sect, oldsect)
			bio.put(f, "[{}]\n", sect)
		;;
		oldsect = sect

		val = std.htgetv(ini.elts, (sect, key), "")
		match bio.put(f, "\t{} = {}\n", key, val)
		| `std.Err e: -> false
		| _:
		;;
	;;
	std.slfree(keys)
	-> true
}