shithub: mc

Download patch

ref: 71bba431594a726d16fe726a71c7c2e7ab6a04d1
parent: 3a884b83d030cd14cf4ee631b5b474fb411c976a
author: Ori Bernstein <[email protected]>
date: Wed Nov 25 19:03:13 EST 2015

Finish fleshing in the inifile API

	- Correctly implement put()
	- Implement write()

--- a/lib/inifile/access.myr
+++ b/lib/inifile/access.myr
@@ -24,6 +24,12 @@
 }
 
 const put = {ini, sect, key, val
-	std.htput(ini.elts, (std.sldup(sect), std.sldup(key)), std.sldup(val))
+	if std.hthas(ini.elts, (sect, key))
+		std.slfree(std.htgetv(ini.elts, (sect, key), ""))
+	else
+		sect = std.sldup(sect)
+		key = std.sldup(key)
+	;;
+	std.htput(ini.elts, (sect, key), std.sldup(val))
 }
 
--- a/lib/inifile/test/inifile.myr
+++ b/lib/inifile/test/inifile.myr
@@ -28,6 +28,10 @@
 	checkval(ini, "another section", "otherkey", "meh1")
 	checkval(ini, "another section", "whatever", "\"more stuff here\"")
 
+	inifile.put(ini, "new sect", "key", "val")
+	/* TODO: check this for validity */
+	std.assert(inifile.write(ini, "test/out.ini"), "failed to write test ini")
+
 	inifile.free(ini)
 }
 
--- a/lib/inifile/write.myr
+++ b/lib/inifile/write.myr
@@ -5,8 +5,58 @@
 
 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.Fail 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) in keys 
+		std.put("sect={}, oldsect={}\n", sect, oldsect)
+		if !std.sleq(sect, oldsect)
+			bio.put(f, "[{}]\n", sect)
+		;;
+		oldsect = sect
+
+		val = std.htgetv(ini.elts, (sect, key), "")
+		match bio.put(f, "\t{} = {}\n", key, val)
+		| `bio.Err e: -> false
+		| _:
+		;;
+	;;
+	std.slfree(keys)
 	-> true
 }