forked from martinroddam/gherkin2markdown
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert.go
105 lines (83 loc) · 2.33 KB
/
convert.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
93
94
95
96
97
98
99
100
101
102
103
104
105
package g2md
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"golang.org/x/sync/errgroup"
"github.com/cucumber/gherkin-go"
)
const featureFileExtension = ".feature"
// Convert reads data from the provided reader, converts it to markdown and returns the result as a string.
func Convert(r io.Reader, ignoreTags ...string) (string, error) {
d, err := gherkin.ParseGherkinDocument(r)
if err != nil {
return "", err
}
return newRenderer(ignoreTags).Render(d), nil
}
// ConvertFileToString loads a file, converts it to markdown and returns the result as a string.
func ConvertFileToString(fileName string, ignoreTags ...string) (string, error) {
f, err := os.Open(fileName)
if err != nil {
return "", err
}
defer f.Close()
return Convert(f, ignoreTags...)
}
// ConvertFile loads a source file, converts it to markdown and writes it to the given destination.
func ConvertFile(sourceName, destName string, ignoreTags ...string) error {
data, err := ConvertFileToString(sourceName, ignoreTags...)
if err != nil {
return err
}
out, err := os.OpenFile(destName, os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return err
}
_, err = fmt.Fprint(out, data)
if err != nil {
_ = out.Close()
return err
}
return out.Close()
}
// ConvertFiles reads all gherkin files in the source directory, converts them to markdown
// and writes the result to the target directory.
func ConvertFiles(sourceDir, destDir string, ignoreTags ...string) error {
var sources []string
err := filepath.Walk(sourceDir, func(p string, i os.FileInfo, err error) error {
if err != nil {
return err
}
if !i.IsDir() && filepath.Ext(p) == featureFileExtension {
sources = append(sources, p)
}
return nil
})
if err != nil {
return err
}
var eg errgroup.Group
for _, source := range sources {
eg.Go(newConvertJob(source, sourceDir, destDir, ignoreTags))
}
return eg.Wait()
}
func newConvertJob(source, sourceDir, destDir string, ignoreTags []string) func() error {
return func() error {
dest, err := filepath.Rel(sourceDir, source)
if err != nil {
return err
}
dest = strings.TrimSuffix(filepath.Join(destDir, dest), featureFileExtension) + ".md"
if err = os.MkdirAll(filepath.Dir(dest), 0700); err != nil {
return err
}
if err = ConvertFile(source, dest, ignoreTags...); err != nil {
return err
}
return nil
}
}