在markdown头部加上 或者 ,即解析markdown中的ul>li>a链接作为目录
(bookIdentify, htmlStr string, bookId int)
| 346 | |
| 347 | // 在markdown头部加上<bookstack></bookstack>或者<bookstack/>,即解析markdown中的ul>li>a链接作为目录 |
| 348 | func (this *BaseController) sortBySummary(bookIdentify, htmlStr string, bookId int) string { |
| 349 | debug := beego.AppConfig.String("runmod") != "prod" |
| 350 | o := orm.NewOrm() |
| 351 | qs := o.QueryTable("md_documents").Filter("book_id", bookId) |
| 352 | doc, err := goquery.NewDocumentFromReader(strings.NewReader(htmlStr)) |
| 353 | if err != nil { |
| 354 | beego.Error(err) |
| 355 | } |
| 356 | idx := 1 |
| 357 | if debug { |
| 358 | beego.Info("根据summary文件进行排序") |
| 359 | } |
| 360 | |
| 361 | //查找ul>li下的所有a标签,并提取text和href,查询数据库,如果标识不存在,则把这些新的数据录入数据库 |
| 362 | var hrefs = make(map[string]string) |
| 363 | var hrefSlice []interface{} |
| 364 | var docs []models.Document |
| 365 | doc.Find("li>a").Each(func(i int, selection *goquery.Selection) { |
| 366 | if href, ok := selection.Attr("href"); ok && strings.HasPrefix(href, "$") { |
| 367 | href = strings.TrimLeft(strings.Replace(href, "/", "-", -1), "$") |
| 368 | if utf8.RuneCountInString(href) <= 100 { |
| 369 | if href == "" { |
| 370 | href = strings.Replace(selection.Text(), " ", "", -1) + ".md" |
| 371 | selection.SetAttr("href", "$"+href) |
| 372 | } |
| 373 | hrefs[href] = selection.Text() |
| 374 | hrefSlice = append(hrefSlice, href) |
| 375 | } |
| 376 | } |
| 377 | }) |
| 378 | if debug { |
| 379 | beego.Info(hrefs) |
| 380 | } |
| 381 | if len(hrefSlice) > 0 { |
| 382 | if _, err := qs.Filter("identify__in", hrefSlice...).Limit(len(hrefSlice)).All(&docs, "identify"); err != nil { |
| 383 | beego.Error(err.Error()) |
| 384 | } else { |
| 385 | for _, doc := range docs { |
| 386 | //删除存在的标识 |
| 387 | delete(hrefs, doc.Identify) |
| 388 | } |
| 389 | } |
| 390 | } |
| 391 | if len(hrefs) > 0 { //存在未创建的文档,先创建 |
| 392 | ModelStore := new(models.DocumentStore) |
| 393 | for identify, docName := range hrefs { |
| 394 | // 如果文档标识超过了规定长度(100),则进行忽略 |
| 395 | if utf8.RuneCountInString(identify) <= 100 { |
| 396 | doc := models.Document{ |
| 397 | BookId: bookId, |
| 398 | Identify: identify, |
| 399 | DocumentName: docName, |
| 400 | CreateTime: time.Now(), |
| 401 | ModifyTime: time.Now(), |
| 402 | } |
| 403 | if docId, err := doc.InsertOrUpdate(); err == nil { |
| 404 | if err = ModelStore.InsertOrUpdate(models.DocumentStore{DocumentId: int(docId), Markdown: "[TOC]\n\r\n\r"}); err != nil { |
| 405 | beego.Error(err.Error()) |
no test coverage detected