变量替换代码片段

代码片段分享


package main

import (
	"bufio"
	"bytes"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"
)

func main() {
	M := ReadStaticAndVariable("staticTovariable")
	if len(os.Args) != 2 {
		println("args error.")
		return
	}
	list, err := GetConfigFiles(os.Args[1])
	if err != nil {
		println(err.Error())
		return
	}
	StaticToVariable(list, M)
}

func GetConfigFiles(path string) ([]string, error) {
	if !strings.HasSuffix(path, "/") {
		path = path + "/"
	}
	var list []string
	files, err := ioutil.ReadDir(path)
	if err != nil {
		return list, err
	}
	for _, v := range files {
		if v.IsDir() {
			continue
		}
		list = append(list, path+v.Name())
	}
	return list, nil
}

func ReadStaticAndVariable(path string) map[string]string {
	File, err := os.Open(path)
	if err != nil {
		return nil
	}
	defer File.Close()
	buf := bufio.NewReader(File)
	M := make(map[string]string)
	for {
		line, _, err := buf.ReadLine()
		if err != nil {
			if err.Error() == "EOF" {
				break
			}
			return nil
		}
		list := bytes.Split(line, []byte("="))
		if len(list) != 2 {
			continue
		}
		k := bytes.TrimSpace(list[0])
		v := bytes.TrimSpace(list[1])
		M[string(k)] = string(v)
	}
	return M
}

//设置并发处理的个数.
const number int = 5

func StaticToVariable(pathList []string, M map[string]string) {
	c := make(chan int, number)
	for _, name := range pathList {
		c <- 1
		go staticToVariable(c, name, M)
	}
	for {
		if len(c) != 0 {
			time.Sleep(1e9)
			continue
		}
		break
	}
}

func staticToVariable(c chan int, path string, M map[string]string) {
	defer func(c chan int) {
		<-c
	}(c)
	path = filepath.ToSlash(path)
	File, err := os.Open(path)
	if err != nil {
		return
	}
	tmpName := filepath.Dir(path) + "/." + filepath.Base(path)
	tmp, err := os.OpenFile(tmpName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		File.Close()
		return
	}
	buf := getBuf()
	defer putBuf(buf)
	for {
		n, err := File.Read(buf)
		if err != nil {
			if err.Error() == "EOF" {
				break
			}
			File.Close()
			return
		}
		for k, v := range M {
			buf = bytes.Replace(buf[:n], []byte(k), []byte(v), -1)
		}
		tmp.Write(bytes.TrimSpace(buf))
		tmp.Sync()
	}
	File.Close()
	tmp.Close()
	os.Remove(path)
	os.Rename(tmpName, path)
	return
}

var BufPool *sync.Pool = new(sync.Pool)

func getBuf() []byte {
	b := BufPool.Get()
	if b != nil {
		return b.([]byte)
	}
	return make([]byte, 512)
}

func putBuf(buf []byte) {
	BufPool.Put(buf)
}

func checkIsBinary(path string) bool {
	File, err := os.Open(path)
	if err != nil {
		return true
	}
	buf := make([]byte, 1024)
	n, err := File.Read(buf)
	if err != nil {
		return true
	}
	if bytes.Contains(buf[:n], []byte{0x0}) {
		return true
	}
	return false
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值