You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
naza/demo/add_blog_license/main.go

99 lines
2.9 KiB
Go

// Copyright 2019, Chef. All rights reserved.
// https://github.com/q191201771/naza
//
// Use of this source code is governed by a MIT-style license
// that can be found in the License file.
//
// Author: Chef (191201771@qq.com)
package main
import (
"bytes"
"flag"
"fmt"
"github.com/q191201771/naza/pkg/filebatch"
"github.com/q191201771/naza/pkg/nazalog"
"os"
)
//var licenseTmpl = `
//> **本文原始地址:** [https://pengrl.com/p/%s/](https://pengrl.com/p/%s/)
//> **声明:** 本文后续所有修改都会第一时间在原始地址更新。本文欢迎任何形式转载,转载时注明原始出处即可。`
var licenseTmpl = `
> **** [https://pengrl.com/p/%s/](https://pengrl.com/p/%s/)
> **** [yoko blog](https://pengrl.com) (https://pengrl.com)
> **** yoko
> **** `
func main() {
dir := parseFlag()
//linesOfLicense := strings.Split(licenseTmpl, "\n")
//lastLineOfLicense := linesOfLicense[len(linesOfLicense)-1]
var (
skipCount int
modCount int
)
err2 := filebatch.Walk(dir, true, ".md", func(path string, info os.FileInfo, content []byte, err error) []byte {
if err != nil {
nazalog.Warnf("read file failed. file=%s, err=%+v", path, err)
return nil
}
lines := bytes.Split(content, []byte{'\n'})
//if bytes.Index(lines[len(lines)-1], []byte("声明")) != -1 {
// res, err := filebatch.DeleteLines(content, filebatch.LineRange{From: -2, To: -1})
// nazalog.Debugf("%s -2", info.Name())
// nazalog.FatalIfErrorNotNil(err)
// return res
//}
//if bytes.Index(lines[len(lines)-2], []byte("声明")) != -1 {
// res, err := filebatch.DeleteLines(content, filebatch.LineRange{From: -3, To: -1})
// nazalog.Debugf("%s -3", info.Name())
// nazalog.FatalIfErrorNotNil(err)
// return res
//}
//nazalog.Warnf("%s", info.Name())
//return content
// 已添加过声明,不用再添加了
if bytes.Index(lines[len(lines)-1], []byte("版权声明")) != -1 ||
bytes.Index(lines[len(lines)-2], []byte("版权声明")) != -1 {
skipCount++
return nil
}
// 获取该文章的url的地址
var abbrlink string
for _, line := range lines {
if bytes.Index(line, []byte("abbrlink")) != -1 {
abbrlink = string(bytes.TrimSpace(bytes.Split(line, []byte{':'})[1]))
nazalog.Debug(abbrlink)
break
}
}
// 构造好license信息并添加在文章末尾
modCount++
license := fmt.Sprintf(licenseTmpl, abbrlink, abbrlink)
return filebatch.AddTailContent(content, []byte(license))
})
nazalog.FatalIfErrorNotNil(err2)
nazalog.Infof("count. mod=%d, skip=%d", modCount, skipCount)
}
func parseFlag() string {
dir := flag.String("d", "", "dir of posts")
flag.Parse()
if *dir == "" {
flag.Usage()
os.Exit(1)
}
return *dir
}