Skip to content

Instantly share code, notes, and snippets.

@reiki4040
Created March 10, 2017 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save reiki4040/2b038462b658b7409dc93cc8ee860fcc to your computer and use it in GitHub Desktop.
Save reiki4040/2b038462b658b7409dc93cc8ee860fcc to your computer and use it in GitHub Desktop.
replace inventory file block for tool.
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"strings"
)
func errExit(msg string) {
println(msg)
os.Exit(1)
}
func main() {
if len(os.Args) != 4 {
errExit("COMMAND <inventory_path> <entry_path> <name>")
}
iPath := os.Args[1]
ePath := os.Args[2]
name := os.Args[3]
err := replace(iPath, ePath, name)
if err != nil {
errExit(err.Error())
}
}
func replace(inventoryPath, entryPath, name string) error {
eFile, err := os.Open(entryPath)
if err != nil {
return err
}
defer eFile.Close()
eStr, err := ioutil.ReadAll(eFile)
if err != nil {
return err
}
iFile, err := os.Open(inventoryPath)
if err != nil {
return err
}
defer iFile.Close()
sc := bufio.NewScanner(iFile)
bName := "[" + name + "]"
inReplace := false
for sc.Scan() {
l := sc.Text()
if l == bName {
inReplace = true
continue
}
if inReplace {
if i := strings.Index(l, "["); i == 0 {
fmt.Println(bName)
fmt.Print(string(eStr))
fmt.Println(l)
inReplace = false
}
} else {
fmt.Println(l)
}
}
if inReplace {
fmt.Println(bName)
fmt.Print(string(eStr))
}
return sc.Err()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment