MCPcopy Index your code
hub / github.com/TruthHun/BookStack / fixFileLinks

Method fixFileLinks

controllers/BookController.go:1239–1319  ·  view source on GitHub ↗

查找并替换markdown文件中的路径,把图片链接替换成url的相对路径,把文档间的链接替换成【$+文档标识链接】

(projectRoot string, identify string)

Source from the content-addressed store, hash-verified

1237
1238// 查找并替换markdown文件中的路径,把图片链接替换成url的相对路径,把文档间的链接替换成【$+文档标识链接】
1239func (this *BookController) fixFileLinks(projectRoot string, identify string) {
1240 imgBaseUrl := "/uploads/projects/" + identify
1241 switch utils.StoreType {
1242 case utils.StoreLocal:
1243 imgBaseUrl = "/uploads/projects/" + identify
1244 case utils.StoreOss:
1245 //imgBaseUrl = this.BaseController.OssDomain + "/projects/" + identify
1246 imgBaseUrl = "/projects/" + identify
1247 }
1248 files, _ := filetil.ScanFiles(projectRoot)
1249 for _, file := range files {
1250 ext := strings.ToLower(filepath.Ext(file.Path))
1251 if !(ext == ".md" || ext == ".markdown" || ext == ".html" || ext == ".xhtml") {
1252 continue
1253 }
1254
1255 //mdb ==> markdown byte
1256 mdb, _ := ioutil.ReadFile(file.Path)
1257 mdCont := string(mdb)
1258 if ext == ".html" || ext == ".xhtml" {
1259 mdCont = html2md.Convert(mdCont)
1260 }
1261
1262 basePath := filepath.Dir(file.Path)
1263 basePath = strings.Trim(strings.Replace(basePath, "\\", "/", -1), "/")
1264 basePathSlice := strings.Split(basePath, "/")
1265 l := len(basePathSlice)
1266 b, _ := ioutil.ReadFile(file.Path)
1267 output := blackfriday.Run(b)
1268 doc, _ := goquery.NewDocumentFromReader(bytes.NewReader(output))
1269
1270 //图片链接处理
1271 doc.Find("img").Each(func(i int, selection *goquery.Selection) {
1272 //非http://、// 和 https:// 开头的图片地址,即是相对地址
1273 src, ok := selection.Attr("src")
1274 lowerSrc := strings.ToLower(src)
1275 if ok &&
1276 !strings.HasPrefix(lowerSrc, "http://") &&
1277 !strings.HasPrefix(lowerSrc, "https://") {
1278 newSrc := src //默认为旧地址
1279 if strings.HasPrefix(lowerSrc, "//") {
1280 newSrc = "https:" + newSrc
1281 } else {
1282 if cnt := strings.Count(src, "../"); cnt < l { //以或者"../"开头的路径
1283 newSrc = strings.Join(basePathSlice[0:l-cnt], "/") + "/" + strings.TrimLeft(src, "./")
1284 }
1285 newSrc = imgBaseUrl + "/" + strings.TrimLeft(strings.TrimPrefix(strings.TrimLeft(newSrc, "./"), projectRoot), "/")
1286 }
1287 mdCont = strings.Replace(mdCont, src, newSrc, -1)
1288 }
1289 })
1290
1291 //a标签链接处理。要注意判断有锚点的情况
1292 doc.Find("a").Each(func(i int, selection *goquery.Selection) {
1293 href, ok := selection.Attr("href")
1294 lowerHref := strings.TrimSpace(strings.ToLower(href))
1295 // 链接存在,且不以 // 、 http、https、mailto 开头
1296 if ok &&

Callers 2

unzipToDataMethod · 0.95
loadByFolderMethod · 0.95

Calls 6

ConvertFunction · 0.92
stringFunction · 0.85
RunMethod · 0.80
ReplaceMethod · 0.45
FindMethod · 0.45
CountMethod · 0.45

Tested by

no test coverage detected