需求,读取wiki目录下的所有子目录,子目录的md根据头部yam的collection字段分组到文件夹。
代码脚本如下:
package main
import (
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"os"
)
type Blog struct {
Title string `yaml:"title"`
Collection string `yaml:"collection"`
}
func ReadYamlConfig(path string) (*Blog, error) {
conf := &Blog{}
if f, err := os.Open(path); err != nil {
return nil, err
} else {
err := yaml.NewDecoder(f).Decode(conf)
if err != nil {
fmt.Println("yaml 解析error:", err)
}
return conf, err
}
}
func main() {
print("start...")
wikiPath := "/Users/panda/hugo-coder/content/wiki"
files, _ := ioutil.ReadDir(wikiPath)
for _, f := range files {
if f.IsDir() {
fmt.Println("当前目录为", f.Name())
subFiles, _ := ioutil.ReadDir(wikiPath + "/" + f.Name())
for _, sf := range subFiles {
if !sf.IsDir() && sf.Name() != ".DS_Store" {
filepathbegin := wikiPath + "/" + f.Name() + "/" + sf.Name()
fmt.Println(filepathbegin)
blog, err := ReadYamlConfig(wikiPath + "/" + f.Name() + "/" + sf.Name())
if err != nil {
fmt.Println("读取yaml失败", err)
}
if blog.Collection != "" {
fmt.Println(blog.Collection)
gpath := wikiPath + "/" + f.Name() + "/" + blog.Collection
filepathend := wikiPath + "/" + f.Name() + "/" + blog.Collection + "/" + sf.Name()
fmt.Println(filepathend)
// 查看目录是否存在
if _, err := os.Stat(gpath); os.IsNotExist(err) {
fmt.Println("目录不存在")
_ = os.Mkdir(gpath, 0755)
_ = os.Rename(filepathbegin, filepathend)
} else {
fmt.Println("目录存在")
_ = os.Rename(filepathbegin, filepathend)
}
}
}
}
fmt.Println("--------------------------")
}
}
}