mirror of
https://github.com/xiaoqidun/goini.git
synced 2026-09-03 08:10:22 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7914cbd743 | ||
|
|
99c0d37995 | ||
|
|
333eff36a2 | ||
|
|
c2ceb7dea7 | ||
|
|
1f9d169cf1 | ||
|
|
ee27859f7e | ||
|
|
96e3375441 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
# GoINI [](https://pkg.go.dev/github.com/xiaoqidun/goini)
|
||||
|
||||
零依赖、够简单的 Go 语言 INI 配置文件读写库
|
||||
够简单、零依赖的 Go 语言 INI 配置文件读写库
|
||||
|
||||
# 安装方法
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ var (
|
||||
|
||||
// GoINI 表示INI配置解析器
|
||||
type GoINI struct {
|
||||
data []byte
|
||||
filename string
|
||||
fileLines []iniLine
|
||||
structTag string
|
||||
@@ -43,8 +42,7 @@ func NewGoINI() *GoINI {
|
||||
// 入参: fileData 配置文件内容
|
||||
func (ini *GoINI) SetData(fileData []byte) {
|
||||
ini.filename = ""
|
||||
ini.data = append(ini.data[:0], fileData...)
|
||||
ini.parse()
|
||||
ini.parse(string(fileData))
|
||||
}
|
||||
|
||||
// LoadFile 从文件读取配置并解析
|
||||
@@ -56,31 +54,43 @@ func (ini *GoINI) LoadFile(filename string) error {
|
||||
return err
|
||||
}
|
||||
ini.filename = filename
|
||||
ini.data = append(ini.data[:0], b...)
|
||||
ini.parse()
|
||||
ini.parse(string(b))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Save 将配置写回LoadFile读取的文件
|
||||
// 返回: error 错误信息
|
||||
func (ini *GoINI) Save() error {
|
||||
if ini.filename == "" {
|
||||
return errFilenameRequired
|
||||
return ini.save(ini.String())
|
||||
}
|
||||
return ini.SaveFile(ini.filename)
|
||||
|
||||
// SaveFormat 将配置格式化并写回LoadFile读取的文件
|
||||
// 返回: error 错误信息
|
||||
func (ini *GoINI) SaveFormat() error {
|
||||
formatted := ini.formatString()
|
||||
if err := ini.save(formatted); err != nil {
|
||||
return err
|
||||
}
|
||||
ini.parse(formatted)
|
||||
return nil
|
||||
}
|
||||
|
||||
// SaveFile 将配置写入指定文件
|
||||
// 入参: filename 配置文件路径
|
||||
// 入参: filename 配置文件路径, perm 文件权限
|
||||
// 返回: error 错误信息
|
||||
func (ini *GoINI) SaveFile(filename string) error {
|
||||
if filename == "" {
|
||||
return errFilenameRequired
|
||||
func (ini *GoINI) SaveFile(filename string, perm os.FileMode) error {
|
||||
return ini.saveFile(filename, ini.String(), perm)
|
||||
}
|
||||
if err := os.WriteFile(filename, []byte(ini.String()), 0o666); err != nil {
|
||||
|
||||
// SaveFormatFile 将配置格式化并写入指定文件
|
||||
// 入参: filename 配置文件路径, perm 文件权限
|
||||
// 返回: error 错误信息
|
||||
func (ini *GoINI) SaveFormatFile(filename string, perm os.FileMode) error {
|
||||
formatted := ini.formatString()
|
||||
if err := ini.saveFile(filename, formatted, perm); err != nil {
|
||||
return err
|
||||
}
|
||||
ini.filename = filename
|
||||
ini.parse(formatted)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -106,7 +116,7 @@ func (ini *GoINI) SetString(name string, key string, value string) {
|
||||
if index, ok := ini.findSectionKeyLineIndex(name, key); ok {
|
||||
ini.fileLines[index].keyValue = value
|
||||
ini.fileLines[index].modified = true
|
||||
ini.rebuildIndexes()
|
||||
ini.sectionValues[name][key] = value
|
||||
return
|
||||
}
|
||||
ini.ensureSectionLine(name)
|
||||
@@ -183,6 +193,24 @@ func (ini *GoINI) GetNameKeys(name string, match string) []string {
|
||||
return matchStrings(ini.sectionKeys[name], match)
|
||||
}
|
||||
|
||||
// HasSection 判断分区是否存在
|
||||
// 入参: name 分区名称
|
||||
// 返回: bool 是否存在
|
||||
func (ini *GoINI) HasSection(name string) bool {
|
||||
name = ini.normalizeSection(name)
|
||||
_, ok := ini.sectionValues[name]
|
||||
return ok
|
||||
}
|
||||
|
||||
// HasKey 判断分区下配置项是否存在
|
||||
// 入参: name 分区名称, key 配置项名称
|
||||
// 返回: bool 是否存在
|
||||
func (ini *GoINI) HasKey(name string, key string) bool {
|
||||
name = ini.normalizeSection(name)
|
||||
_, ok := ini.sectionValues[name][key]
|
||||
return ok
|
||||
}
|
||||
|
||||
// GetString 获取单个配置项的字符串值
|
||||
// 入参: name 分区名称, key 配置项名称, value 默认值
|
||||
// 返回: string 配置项值
|
||||
@@ -288,3 +316,19 @@ func (ini *GoINI) MapToStruct(ptr interface{}) error {
|
||||
ini.mapStruct(v)
|
||||
return nil
|
||||
}
|
||||
|
||||
// MapSectionToStruct 将指定分区映射到一个结构体
|
||||
// 入参: name 分区名称, ptr 结构体指针
|
||||
// 返回: error 错误信息
|
||||
func (ini *GoINI) MapSectionToStruct(name string, ptr interface{}) error {
|
||||
v := reflect.ValueOf(ptr)
|
||||
if !v.IsValid() || v.Kind() != reflect.Ptr || v.IsNil() {
|
||||
return errStructPointerRequired
|
||||
}
|
||||
v = v.Elem()
|
||||
if v.Kind() != reflect.Struct {
|
||||
return errStructPointerRequired
|
||||
}
|
||||
ini.mapSection(v, ini.normalizeSection(name))
|
||||
return nil
|
||||
}
|
||||
+103
-14
@@ -1,6 +1,8 @@
|
||||
package goini
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
@@ -36,14 +38,14 @@ type parsedKeyValue struct {
|
||||
separator string
|
||||
}
|
||||
|
||||
func (ini *GoINI) parse() {
|
||||
func (ini *GoINI) parse(data string) {
|
||||
ini.fileLines = nil
|
||||
currentSection := ini.rootSection
|
||||
if len(ini.data) == 0 {
|
||||
if data == "" {
|
||||
ini.rebuildIndexes()
|
||||
return
|
||||
}
|
||||
for _, rawLine := range strings.Split(string(ini.data), "\n") {
|
||||
for _, rawLine := range strings.Split(data, "\n") {
|
||||
line, section := parseRawLine(rawLine, currentSection)
|
||||
currentSection = section
|
||||
ini.fileLines = append(ini.fileLines, line)
|
||||
@@ -68,6 +70,9 @@ func parseRawLine(rawLine string, sectionName string) (iniLine, string) {
|
||||
line.sectionName = nextSection
|
||||
return line, nextSection
|
||||
}
|
||||
if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") {
|
||||
return line, sectionName
|
||||
}
|
||||
if parsed, ok := parseKeyValue(rawLine); ok {
|
||||
line.kind = lineKeyValue
|
||||
line.keyName = parsed.key
|
||||
@@ -187,7 +192,7 @@ func (ini *GoINI) addSectionKey(sectionName string, keyName string, keyValue str
|
||||
|
||||
func (ini *GoINI) ensureParsed() {
|
||||
if ini.sectionValues == nil {
|
||||
ini.parse()
|
||||
ini.parse("")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,9 +209,6 @@ func (ini *GoINI) findSectionLineIndex(sectionName string) (int, bool) {
|
||||
}
|
||||
|
||||
func (ini *GoINI) findSectionKeyLineIndex(sectionName string, keyName string) (int, bool) {
|
||||
if ini.sectionKeyLineIndexes[sectionName] == nil {
|
||||
return 0, false
|
||||
}
|
||||
index, ok := ini.sectionKeyLineIndexes[sectionName][keyName]
|
||||
return index, ok
|
||||
}
|
||||
@@ -234,6 +236,9 @@ func (ini *GoINI) findSectionInsertIndex(sectionName string) int {
|
||||
insert := len(ini.fileLines)
|
||||
for i, line := range ini.fileLines {
|
||||
if line.kind == lineSection {
|
||||
if current == sectionName {
|
||||
insert, _ = ini.commentRangeBefore(i)
|
||||
}
|
||||
current = line.sectionName
|
||||
if current == sectionName {
|
||||
insert = i + 1
|
||||
@@ -250,9 +255,13 @@ func (ini *GoINI) findSectionInsertIndex(sectionName string) int {
|
||||
func (ini *GoINI) findRootInsertIndex() int {
|
||||
for i, line := range ini.fileLines {
|
||||
if line.kind == lineSection {
|
||||
return i
|
||||
start, _ := ini.commentRangeBefore(i)
|
||||
return start
|
||||
}
|
||||
}
|
||||
if len(ini.sectionKeys[ini.rootSection]) == 0 {
|
||||
return ini.firstRootLineIndex()
|
||||
}
|
||||
return len(ini.fileLines)
|
||||
}
|
||||
|
||||
@@ -306,7 +315,11 @@ func (ini *GoINI) firstRootLineIndex() int {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return 0
|
||||
index := len(ini.fileLines)
|
||||
for index > 0 && ini.fileLines[index-1].kind == lineBlank {
|
||||
index--
|
||||
}
|
||||
return index
|
||||
}
|
||||
|
||||
func commentLines(comment string) []iniLine {
|
||||
@@ -323,7 +336,7 @@ func commentLines(comment string) []iniLine {
|
||||
|
||||
func formatComment(comment string) string {
|
||||
trimmed := strings.TrimLeftFunc(comment, unicode.IsSpace)
|
||||
if strings.HasPrefix(trimmed, "#") || strings.HasPrefix(trimmed, ";") {
|
||||
if isComment(trimmed) {
|
||||
return comment
|
||||
}
|
||||
if comment == "" {
|
||||
@@ -337,8 +350,7 @@ func stripComment(comment string) string {
|
||||
if !isComment(trimmed) {
|
||||
return trimmed
|
||||
}
|
||||
trimmed = strings.TrimPrefix(strings.TrimPrefix(trimmed, "#"), ";")
|
||||
return strings.TrimPrefix(trimmed, " ")
|
||||
return strings.TrimPrefix(trimmed[1:], " ")
|
||||
}
|
||||
|
||||
func renderLine(line iniLine) string {
|
||||
@@ -360,10 +372,14 @@ func renderLine(line iniLine) string {
|
||||
|
||||
func renderKeyValue(line iniLine) string {
|
||||
separator := line.separator
|
||||
if separator == "" {
|
||||
if separator == "" || !strings.Contains(separator, "=") && strings.Contains(line.keyValue, "=") {
|
||||
separator = defaultSeparator
|
||||
}
|
||||
return line.indent + line.keyName + separator + formatValue(line.keyValue)
|
||||
value := formatValue(line.keyValue)
|
||||
if strings.HasPrefix(line.keyName, "[") && strings.HasSuffix(value, "]") {
|
||||
value = `"` + value + `"`
|
||||
}
|
||||
return line.indent + line.keyName + separator + value
|
||||
}
|
||||
|
||||
func formatValue(value string) string {
|
||||
@@ -377,6 +393,79 @@ func formatValue(value string) string {
|
||||
return quote + value + quote
|
||||
}
|
||||
|
||||
func (ini *GoINI) formatString() string {
|
||||
formattedLines := make([]string, 0, len(ini.fileLines))
|
||||
pendingComments := make([]string, 0)
|
||||
for _, line := range ini.fileLines {
|
||||
switch line.kind {
|
||||
case lineSection:
|
||||
if len(formattedLines) > 0 {
|
||||
formattedLines = append(formattedLines, "")
|
||||
}
|
||||
formattedLines = append(formattedLines, pendingComments...)
|
||||
pendingComments = pendingComments[:0]
|
||||
formattedLines = append(formattedLines, "["+line.sectionName+"]")
|
||||
case lineKeyValue:
|
||||
formattedLines = append(formattedLines, pendingComments...)
|
||||
pendingComments = pendingComments[:0]
|
||||
line.indent = ""
|
||||
line.separator = defaultSeparator
|
||||
formattedLines = append(formattedLines, renderKeyValue(line))
|
||||
case lineComment:
|
||||
pendingComments = append(pendingComments, formatINIComment(line.text))
|
||||
}
|
||||
}
|
||||
formattedLines = append(formattedLines, pendingComments...)
|
||||
if len(formattedLines) == 0 {
|
||||
return ""
|
||||
}
|
||||
return strings.Join(formattedLines, "\n") + "\n"
|
||||
}
|
||||
|
||||
func formatINIComment(comment string) string {
|
||||
comment = stripComment(comment)
|
||||
if comment == "" {
|
||||
return "#"
|
||||
}
|
||||
return "# " + comment
|
||||
}
|
||||
|
||||
func (ini *GoINI) save(data string) error {
|
||||
if ini.filename == "" {
|
||||
return errFilenameRequired
|
||||
}
|
||||
info, err := os.Stat(ini.filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ini.saveFile(ini.filename, data, info.Mode().Perm())
|
||||
}
|
||||
|
||||
func (ini *GoINI) saveFile(filename string, data string, perm os.FileMode) error {
|
||||
if filename == "" {
|
||||
return errFilenameRequired
|
||||
}
|
||||
perm = perm.Perm()
|
||||
writePerm := perm | 0o200
|
||||
if info, err := os.Stat(filename); err == nil {
|
||||
if info.Mode().IsRegular() {
|
||||
if err := os.Chmod(filename, writePerm); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(filename, []byte(data), writePerm); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Chmod(filename, perm); err != nil {
|
||||
return err
|
||||
}
|
||||
ini.filename = filename
|
||||
return nil
|
||||
}
|
||||
|
||||
func matchStrings(items []string, match string) []string {
|
||||
if match == "" {
|
||||
return cloneStrings(items)
|
||||
|
||||
Reference in New Issue
Block a user