Skip to content

Commit

Permalink
Implementing Stringer interface to ini parser
Browse files Browse the repository at this point in the history
  • Loading branch information
RawanMostafa08 committed Sep 16, 2024
1 parent 2820ee9 commit 3d13570
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
8 changes: 5 additions & 3 deletions pkg/iniparser.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,9 +162,11 @@ func (i iniParser) Set(sectionName string, key string, value string) error {
return nil
}


// ToString is a method that returns the parsed ini map of the caller object as one string
// The returned string won't include the comments
func (i iniParser) ToString() string {
// Also,it tells fmt pkg how to print the object
func (i iniParser) String() string {
var result string
sectionNames := make([]string, 0)
for sectionName := range i.sections {
Expand All @@ -183,7 +185,7 @@ func (i iniParser) ToString() string {
result += key + " = " + i.sections[sectionName].map_[key] + "\n"
}
}
return result
return fmt.Sprint(result)
}

// SaveToFile is a method that takes a path to an output file and returns an error
Expand All @@ -200,7 +202,7 @@ func (i iniParser) SaveToFile(path string) error {
}
defer file.Close()

stringFile := i.ToString()
stringFile := i.String()
_, err = file.WriteString(stringFile)
if err != nil {
return fmt.Errorf("error in writing to the file: %v", err)
Expand Down
8 changes: 5 additions & 3 deletions pkg/iniparser_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package iniparser

import (
"fmt"
"os"
"reflect"
"testing"
Expand Down Expand Up @@ -301,16 +302,17 @@ func TestSet(t *testing.T) {

}

func TestToString(t *testing.T) {
func TestString(t *testing.T) {
parser1 := InitParser()
parser2 := InitParser()

parser1.LoadFromString(stringINI)
got := parser1.ToString()
got := parser1.String()

parser2.LoadFromString(got)

assertEquality(t, parser1.sections, parser2.sections)
assertEquality(t, fmt.Sprint(parser1), fmt.Sprint(parser2))
}

func TestSaveToFile(t *testing.T) {
Expand All @@ -326,6 +328,6 @@ func TestSaveToFile(t *testing.T) {
t.Errorf("Error! %v", err)
}

stringFile := parser.ToString()
stringFile := parser.String()
assertFile(t, outPath, stringFile)
}

0 comments on commit 3d13570

Please sign in to comment.