-
-
Save xigang/9042f1774de69e6987cac043f88f748a to your computer and use it in GitHub Desktop.
replace inventory file block for tool.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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