~shulhan/asciidoctor-go

37563af4c7e82fab352f4ab9137f808058e483e2 — Shulhan a month ago 013bf4d
all: fix reading include file when parent path is absolute

Previously, if the parent document is opened using absolute path and it
contains include directive, the included file will fail to read because
the parent path is joined with current working directory.
5 files changed, 49 insertions(+), 11 deletions(-)

M document.go
M element_include.go
A element_include_test.go
A testdata/include.adoc
M testdata/include_test.txt
M document.go => document.go +0 -8
@@ 8,7 8,6 @@ import (
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"


@@ 96,7 95,6 @@ func newDocument() (doc *Document) {
func Open(file string) (doc *Document, err error) {
	var (
		fi  os.FileInfo
		wd  string
		raw []byte
	)



@@ 110,13 108,7 @@ func Open(file string) (doc *Document, err error) {
		return nil, fmt.Errorf(`Open %s: %w`, file, err)
	}

	wd, err = os.Getwd()
	if err != nil {
		return nil, fmt.Errorf(`Open %s: %w`, file, err)
	}

	doc = newDocument()
	doc.fpath = filepath.Join(wd, file)
	doc.file = file
	doc.Attributes.Entry[docAttrLastUpdateValue] = fi.ModTime().Round(time.Second).Format(`2006-01-02 15:04:05 Z0700`)


M element_include.go => element_include.go +1 -1
@@ 44,7 44,7 @@ func parseInclude(doc *Document, line []byte) (el *elementInclude) {
	el.attrs.parseElementAttribute(line[start : start+end+1])

	path = applySubstitutions(doc, path)
	el.fpath = filepath.Join(filepath.Dir(doc.fpath), string(path))
	el.fpath = filepath.Join(filepath.Dir(doc.file), string(path))

	el.content, err = os.ReadFile(el.fpath)
	if err != nil {

A element_include_test.go => element_include_test.go +43 -0
@@ 0,0 1,43 @@
package asciidoctor

import (
	"bytes"
	"os"
	"path/filepath"
	"testing"

	"git.sr.ht/~shulhan/pakakeh.go/lib/test"
)

func TestParseIncludeWithAbsolutePath(t *testing.T) {
	var (
		tdata *test.Data
		err   error
	)
	tdata, err = test.LoadData(`testdata/include_test.txt`)
	if err != nil {
		t.Fatal(err)
	}

	var wd string

	wd, err = os.Getwd()
	if err != nil {
		t.Fatal(err)
	}

	var fadoc = filepath.Join(wd, `testdata`, `include.adoc`)
	var doc *Document

	doc, err = Open(fadoc)
	if err != nil {
		t.Fatal(err)
	}

	var got bytes.Buffer

	doc.ToHTMLEmbedded(&got)

	var exp = string(tdata.Output[`include`])
	test.Assert(t, `ParseIncludeWithAbsolutePath`, exp, got.String())
}

A testdata/include.adoc => testdata/include.adoc +3 -0
@@ 0,0 1,3 @@
include::_includes/list_desc_00.adoc[]

include::_includes/list_desc_01.adoc[]

M testdata/include_test.txt => testdata/include_test.txt +2 -2
@@ 1,12 1,12 @@
Test include directive with list description that contains open block.

>>> list_description
>>> include

include::testdata/_includes/list_desc_00.adoc[]

include::testdata/_includes/list_desc_01.adoc[]

<<< list_description
<<< include

<div class="dlist">
<dl>