sync: import files in markdown, relative to theme/exercice dir
This commit is contained in:
parent
8c95782eff
commit
87471acf98
6 changed files with 75 additions and 8 deletions
66
admin/sync/markdown.go
Normal file
66
admin/sync/markdown.go
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
package sync
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/base32"
|
||||
"log"
|
||||
"os"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"srs.epita.fr/fic-server/libfic"
|
||||
|
||||
"golang.org/x/crypto/blake2b"
|
||||
"gopkg.in/russross/blackfriday.v2"
|
||||
)
|
||||
|
||||
func ProcessMarkdown(i Importer, input string, rootDir string) (output string) {
|
||||
// Define the path where save linked files
|
||||
hash := blake2b.Sum512([]byte(rootDir))
|
||||
absPath := "$FILES$/" + strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(hash[:]))
|
||||
|
||||
// Process md
|
||||
output = string(blackfriday.Run(
|
||||
[]byte(input),
|
||||
blackfriday.WithRenderer(blackfriday.NewHTMLRenderer(
|
||||
blackfriday.HTMLRendererParameters{
|
||||
AbsolutePrefix: absPath,
|
||||
Flags: blackfriday.CommonHTMLFlags,
|
||||
},
|
||||
)),
|
||||
))
|
||||
|
||||
// Import files
|
||||
re, err := regexp.Compile(strings.Replace(absPath, "$", "\\$", -1) + "/[^\"]+")
|
||||
if err != nil {
|
||||
log.Println("Unable to compile regexp:", err)
|
||||
return
|
||||
}
|
||||
files := re.FindAllString(output, -1)
|
||||
|
||||
for _, filePath := range files {
|
||||
iPath := strings.TrimPrefix(filePath, absPath)
|
||||
dPath := path.Join(fic.FilesDir, strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(hash[:])), iPath)
|
||||
|
||||
if err := os.MkdirAll(path.Dir(dPath), 0755); err != nil {
|
||||
log.Println("Unable to make directories:", err)
|
||||
return
|
||||
}
|
||||
|
||||
if fdto, err := os.Create(dPath); err != nil {
|
||||
log.Println("Unable to create destination file:", err)
|
||||
return
|
||||
} else {
|
||||
defer fdto.Close()
|
||||
writer := bufio.NewWriter(fdto)
|
||||
if err := getFile(i, rootDir + iPath, writer); err != nil {
|
||||
os.Remove(dPath)
|
||||
log.Println("Unable to create destination file:", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
Reference in a new issue