Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 077e75d

Browse files
author
GANG WANG
committed
feat:wirite ini format
1 parent fca8c1c commit 077e75d

File tree

3 files changed

+82
-4
lines changed

3 files changed

+82
-4
lines changed

ini.go

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"encoding/json"
55
"fmt"
66
"io/ioutil"
7+
"os"
78
"strconv"
89
"strings"
910

@@ -376,11 +377,53 @@ func (this *Ini) DelSection(section string) *Ini {
376377

377378
// TODO: implement Save
378379
func (this *Ini) Save(filename string) *Ini {
379-
return this
380-
}
381380

382-
// TODO: implement SaveFile
383-
func (this *Ini) SaveFile(filename string) *Ini {
381+
if filename == "" {
382+
return this
383+
}
384+
385+
if this.doc == nil {
386+
return this
387+
}
388+
389+
var result string
390+
391+
is_last_type_comment := false
392+
for c := this.doc.FirstChild(); c != nil; c = c.NextSibling() {
393+
if kv_node, ok := c.(*ast.KVNode); ok {
394+
is_last_type_comment = false
395+
result = fmt.Sprintf("%s%s = %v\n", result, kv_node.Key.Literal, kv_node.Value.Literal)
396+
continue
397+
}
398+
399+
if sect_node, ok := c.(*ast.SetcionNode); ok {
400+
is_last_type_comment = false
401+
result = fmt.Sprintf("%s[%s]\n", result, sect_node.Name.Literal)
402+
403+
for c := sect_node.FirstChild(); c != nil; c = c.NextSibling() {
404+
if kv_node, ok := c.(*ast.KVNode); ok {
405+
result = fmt.Sprintf("%s%s = %v\n", result, kv_node.Key.Literal, kv_node.Value.Literal)
406+
continue
407+
}
408+
}
409+
410+
continue
411+
}
412+
413+
if comm_node, ok := c.(*ast.CommentNode); ok {
414+
if !is_last_type_comment {
415+
result = fmt.Sprintf("%s\n", result)
416+
}
417+
418+
is_last_type_comment = true
419+
result = fmt.Sprintf("%s%s\n", result, comm_node.Comment.Literal)
420+
}
421+
}
422+
423+
os.Remove(filename)
424+
var data = []byte(result)
425+
this.err = ioutil.WriteFile(filename, data, 0666)
426+
384427
return this
385428
}
386429

ini_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,3 +237,25 @@ c=d
237237
ini.Dump()
238238

239239
}
240+
241+
func TestIniSave(t *testing.T) {
242+
doc := `
243+
; 123
244+
c11=d12312312
245+
# 434
246+
247+
[section]
248+
k=v
249+
; dsfads
250+
;123
251+
#3452345
252+
253+
254+
[section1]
255+
k1=v1
256+
`
257+
ini := New().Load([]byte(doc))
258+
ini.Dump()
259+
260+
ini.Save("./save.ini")
261+
}

save.ini

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
2+
; 123
3+
c11 = d12312312
4+
5+
# 434
6+
[section]
7+
k = v
8+
9+
; dsfads
10+
;123
11+
#3452345
12+
[section1]
13+
k1 = v1

0 commit comments

Comments
 (0)