forked from dunglas/calavera
/
app.go
92 lines (71 loc) · 1.77 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"github.com/dunglas/calavera/extractor"
"github.com/dunglas/calavera/schema"
)
func main() {
flag.Usage = func() {
fmt.Println("calavera input_directory output_directory")
}
prettifyBool := flag.Bool("prettify", false, "Prettify json output")
flag.Parse()
if len(flag.Args()) != 2 {
log.Fatalln("Input and output directories are mandatory arguments.")
}
var files []string
var extractors = []extractor.Extractor{extractor.Markdown{}, extractor.Git{}}
walkFunc := func(path string, _ os.FileInfo, err error) error {
if nil == err && strings.HasSuffix(path, ".md") {
files = append(files, path)
}
return nil
}
if err := filepath.Walk(flag.Arg(0), walkFunc); nil != err {
check(err)
}
var wg sync.WaitGroup
for _, file := range files {
wg.Add(1)
go func(file string) {
convert(file, flag.Arg(1), extractors, *prettifyBool)
defer wg.Done()
}(file)
}
wg.Wait()
}
func convert(path string, outputDirectory string, extractors []extractor.Extractor, prettify bool) {
creativeWork := schema.NewCreativeWork()
for _, extractor := range extractors {
err := extractor.Extract(creativeWork, path)
check(err)
}
var jsonContent []byte
var err error
if prettify {
jsonContent, err = json.MarshalIndent(creativeWork, "", "\t")
} else {
jsonContent, err = json.Marshal(creativeWork)
}
check(err)
outputPath := fmt.Sprint(outputDirectory, "/", path[:len(path) - 3], ".jsonld")
outputSubdirectory := filepath.Dir(outputPath)
err = os.MkdirAll(outputSubdirectory, 0755)
check(err)
err = ioutil.WriteFile(outputPath, jsonContent, 0644)
check(err)
}
func check(err error) {
if err != nil {
log.Fatalln(err)
panic(err)
}
}