72 lines
1.9 KiB
Python
72 lines
1.9 KiB
Python
import os
|
|
|
|
p = r"E:\GitHub\blog\write-go\cmd\writeserver\main.go"
|
|
with open(p, "r", encoding="utf-8") as f:
|
|
c = f.read()
|
|
|
|
# 1. Add logutil import
|
|
old = '"write-server/internal/images"'
|
|
new = '"write-server/internal/logutil"\n\t"write-server/internal/images"'
|
|
c = c.replace(old, new, 1)
|
|
|
|
# 2. Replace main start to add logging
|
|
old_func = 'func main() {\n\tconfig.Init()\n\trecycle.InitRecycleBin()'
|
|
new_func = '''var log = logutil.Logger
|
|
|
|
func main() {
|
|
\tlog.Info("WriteServer starting")
|
|
\tconfig.Init()
|
|
\trecycle.InitRecycleBin()
|
|
|
|
\tgo autoStartBot()'''
|
|
c = c.replace(old_func, new_func, 1)
|
|
|
|
# 3. Append autoStartBot and helper at end of file
|
|
auto_start = '''
|
|
|
|
func autoStartBot() {
|
|
\ttime.Sleep(2 * time.Second)
|
|
\tbotPort := 8017
|
|
\tif helpersCheckPort(botPort) {
|
|
\t\tlog.Info("bot-go already running", "port", botPort)
|
|
\t\treturn
|
|
\t}
|
|
\tlog.Info("bot-go not responding, starting")
|
|
\tpaths := []string{
|
|
\t\tfilepath.Join(config.BLOG_ROOT, "bot-go", "writebot.exe"),
|
|
\t\tfilepath.Join(config.BLOG_ROOT, "write-go", "writebot.exe"),
|
|
\t}
|
|
\tfor _, p := range paths {
|
|
\t\tif _, err := os.Stat(p); err == nil {
|
|
\t\t\tcmd := exec.Command(p)
|
|
\t\t\tcmd.Dir = filepath.Dir(p)
|
|
\t\t\tif err := cmd.Start(); err != nil {
|
|
\t\t\t\tlog.Error("failed to start bot-go", "err", err)
|
|
\t\t\t} else {
|
|
\t\t\t\tlog.Info("bot-go started", "pid", cmd.Process.Pid)
|
|
\t\t\t}
|
|
\t\t\treturn
|
|
\t\t}
|
|
\t}
|
|
}
|
|
|
|
func helpersCheckPort(port int) bool {
|
|
\tconn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", port), time.Second)
|
|
\tif err != nil {
|
|
\t\treturn false
|
|
\t}
|
|
\tconn.Close()
|
|
\treturn true
|
|
}
|
|
'''
|
|
c += auto_start
|
|
|
|
# 4. Ensure "net" is imported
|
|
if '"net"' not in c[:c.find("func main")]:
|
|
c = c.replace('import (\n\t"encoding/json"', 'import (\n\t"net"\n\t"encoding/json"', 1)
|
|
|
|
with open(p, "w", encoding="utf-8", newline="\n") as f:
|
|
f.write(c)
|
|
print("Patched write-server main.go")
|
|
print("New file size:", len(c.splitlines()), "lines")
|