sync: refactor exercice synchronization

This commit is contained in:
nemunaire 2018-12-05 05:02:27 +01:00
parent 5b53fbda0b
commit dc4a4925e3
5 changed files with 254 additions and 151 deletions

View file

@ -3,7 +3,6 @@ package sync
import (
"bufio"
"encoding/base32"
"log"
"os"
"path"
"regexp"
@ -15,7 +14,7 @@ import (
"gopkg.in/russross/blackfriday.v2"
)
func ProcessMarkdown(i Importer, input string, rootDir string) (output string) {
func ProcessMarkdown(i Importer, input string, rootDir string) (output string, err error) {
// Define the path where save linked files
hash := blake2b.Sum512([]byte(rootDir))
absPath := "$FILES$/" + strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(hash[:]))
@ -32,9 +31,9 @@ func ProcessMarkdown(i Importer, input string, rootDir string) (output string) {
))
// Import files
re, err := regexp.Compile(strings.Replace(absPath, "$", "\\$", -1) + "/[^\"]+")
var re *regexp.Regexp
re, err = regexp.Compile(strings.Replace(absPath, "$", "\\$", -1) + "/[^\"]+")
if err != nil {
log.Println("Unable to compile regexp:", err)
return
}
files := re.FindAllString(output, -1)
@ -43,20 +42,18 @@ func ProcessMarkdown(i Importer, input string, rootDir string) (output string) {
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)
if err = os.MkdirAll(path.Dir(dPath), 0755); err != nil {
return
}
if fdto, err := os.Create(dPath); err != nil {
log.Println("Unable to create destination file:", err)
var fdto *os.File
if fdto, err = os.Create(dPath); err != nil {
return
} else {
defer fdto.Close()
writer := bufio.NewWriter(fdto)
if err := getFile(i, rootDir + iPath, writer); err != nil {
if err = getFile(i, rootDir + iPath, writer); err != nil {
os.Remove(dPath)
log.Println("Unable to create destination file:", err)
return
}
}