Add code package with Parse function (with tests)

This commit is contained in:
Maas Lalani
2021-06-12 22:57:47 -04:00
parent 631057b5cb
commit 2a4ea2ed9d
2 changed files with 114 additions and 0 deletions

35
internal/code/code.go Normal file
View File

@@ -0,0 +1,35 @@
package code
import (
"errors"
"regexp"
)
type Block struct {
Code string
Language string
}
// ?: means non-capture group
var re = regexp.MustCompile("(?:```|~~~)(.*)\n(.*)\n(?:```|~~~)")
var (
ErrParse = errors.New("Error: could not parse code block")
)
// Parse takes a block of markdown and returns an array of Block's with code
// and associated languages
func Parse(markdown string) (Block, error) {
match := re.FindStringSubmatch(markdown)
// There was either no language specified or no code block
// Either way, we cannot execute the expression
if len(match) < 3 {
return Block{}, ErrParse
}
return Block{
Language: match[1],
Code: match[2],
}, nil
}

View File

@@ -0,0 +1,79 @@
package code_test
import (
"testing"
"github.com/maaslalani/slides/internal/code"
)
func TestParse(t *testing.T) {
tt := []struct {
markdown string
expected code.Block
}{
// We can't put backticks ```
// in multi-line strings, ~~~ instead
{
markdown: `
~~~ruby
puts "Hello, world!"
~~~
`,
expected: code.Block{
Code: `puts "Hello, world!"`,
Language: "ruby",
},
},
{
markdown: `
~~~go
fmt.Println("Hello, world!")
~~~
`,
expected: code.Block{
Code: `fmt.Println("Hello, world!")`,
Language: "go",
},
},
{
markdown: `
# Slide 1
Just a regular slide, no code block
`,
expected: code.Block{},
},
{
markdown: `
# Multiple Code Blocks
~~~go
fmt.Println("Oh no!")
~~~
# Secondary Code Block
~~~ruby
puts "We will only parse the first code block"
~~~
`,
expected: code.Block{
Code: `fmt.Println("Oh no!")`,
Language: "go",
},
},
{
markdown: ``,
expected: code.Block{},
},
}
for _, tc := range tt {
b, _ := code.Parse(tc.markdown)
if b.Code != tc.expected.Code {
t.Log(b.Code)
t.Log(tc.expected.Code)
t.Fatal("parse failed: incorrect code")
}
if b.Language != tc.expected.Language {
t.Fatalf("incorrect language, got %s, want %s", b.Language, tc.expected.Language)
}
}
}