2020-04-25 23:42:14 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
2020-04-27 11:35:10 +00:00
|
|
|
"path/filepath"
|
2020-04-25 23:42:14 +00:00
|
|
|
|
|
|
|
"multini/types"
|
|
|
|
)
|
|
|
|
|
|
|
|
func replaceOriginal(oldFile, newFile string) error {
|
2020-04-27 11:35:10 +00:00
|
|
|
realOldFile, err := filepath.EvalSymlinks(oldFile)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
infoOldFile, err := os.Stat(realOldFile)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
mode := infoOldFile.Mode()
|
|
|
|
|
|
|
|
var uid, gid int = GetUidGid(infoOldFile)
|
|
|
|
|
|
|
|
err = os.Remove(realOldFile)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
err = os.Rename(newFile, realOldFile)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
err = os.Chmod(realOldFile, mode)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2020-04-25 23:42:14 +00:00
|
|
|
}
|
2020-04-27 11:35:10 +00:00
|
|
|
|
|
|
|
// try to restore original uid/gid
|
|
|
|
// don't worry if we can't
|
|
|
|
os.Chown(realOldFile, uid, gid)
|
|
|
|
|
2020-04-25 23:42:14 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func iniWrite(filename string, ini *types.Ini) error {
|
|
|
|
tmpFile, err := ioutil.TempFile(os.TempDir(), "multini")
|
|
|
|
if err == nil {
|
|
|
|
datawriter := bufio.NewWriter(tmpFile)
|
|
|
|
_, err = datawriter.WriteString(ini.Full())
|
|
|
|
if err == nil {
|
|
|
|
err = datawriter.Flush()
|
|
|
|
tmpFile.Close()
|
|
|
|
if err == nil {
|
|
|
|
err = replaceOriginal(filename, tmpFile.Name())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func iniWriteInplace(filename string, ini *types.Ini) error {
|
2020-04-27 11:35:10 +00:00
|
|
|
realfilename, err := filepath.EvalSymlinks(filename)
|
|
|
|
mode := os.FileMode(int(0644))
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
realfilename = filename
|
|
|
|
} else if err != nil {
|
|
|
|
return err
|
|
|
|
} else {
|
|
|
|
info, err := os.Stat(realfilename)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
mode = info.Mode()
|
|
|
|
}
|
|
|
|
targetFile, err := os.OpenFile(realfilename, os.O_WRONLY|os.O_CREATE, mode)
|
2020-04-25 23:42:14 +00:00
|
|
|
if err == nil {
|
|
|
|
datawriter := bufio.NewWriter(targetFile)
|
|
|
|
_, err = datawriter.WriteString(ini.Full())
|
|
|
|
if err == nil {
|
|
|
|
err = datawriter.Flush()
|
|
|
|
targetFile.Close()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|