Merge pull request #1393 from nhooyr/import-fixes

Import fixes
This commit is contained in:
Alexander Wang 2023-06-09 20:09:27 -07:00 committed by GitHub
commit 21f59a673c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 22 additions and 25 deletions

View file

@ -6,7 +6,6 @@ import (
"io" "io"
"io/fs" "io/fs"
"net/url" "net/url"
"os"
"strconv" "strconv"
"strings" "strings"
@ -32,9 +31,6 @@ func Compile(p string, r io.RuneReader, opts *CompileOptions) (*d2graph.Graph, e
if opts == nil { if opts == nil {
opts = &CompileOptions{} opts = &CompileOptions{}
} }
if opts.FS == nil {
opts.FS = os.DirFS("/")
}
ast, err := d2parser.Parse(p, r, &d2parser.ParseOptions{ ast, err := d2parser.Parse(p, r, &d2parser.ParseOptions{
UTF16: opts.UTF16, UTF16: opts.UTF16,

View file

@ -216,6 +216,12 @@ func (p *printer) _import(i *d2ast.Import) {
p.sb.WriteString(pre) p.sb.WriteString(pre)
p.sb.WriteRune('/') p.sb.WriteRune('/')
} }
if len(i.Path) > 0 {
i2 := *i
i2.Path = append([]*d2ast.StringBox{}, i.Path...)
i2.Path[0] = d2ast.RawStringBox(path.Clean(i.Path[0].Unbox().ScalarString()), true)
i = &i2
}
p.path(i.Path) p.path(i.Path)
} }

View file

@ -649,6 +649,14 @@ x: @./file
x: @../file x: @../file
`, `,
exp: `x: @../file exp: `x: @../file
`,
},
{
name: "import/4",
in: `
x: @"x/../file"
`,
exp: `x: @file
`, `,
}, },
} }

View file

@ -2,6 +2,7 @@ package d2ir
import ( import (
"bufio" "bufio"
"io/fs"
"os" "os"
"path" "path"
"strings" "strings"
@ -85,25 +86,13 @@ func (c *compiler) __import(imp *d2ast.Import) (*Map, bool) {
return ir, true return ir, true
} }
p := path.Clean(impPath) var f fs.File
if path.IsAbs(p) { var err error
// Path cannot be absolute. DirFS does not accept absolute paths. We strip off the leading if c.fs == nil {
// slash to make it relative to the root. f, err = os.Open(impPath)
p = p[1:] } else {
} else if c.fs == os.DirFS("/") { f, err = c.fs.Open(impPath)
wd, err := os.Getwd()
if err != nil {
c.errorf(imp, "failed to import %q: %v", impPath, err)
return nil, false
}
p = path.Join(wd, p)
// See above explanation.
if path.IsAbs(p) {
p = p[1:]
}
} }
f, err := c.fs.Open(p)
if err != nil { if err != nil {
c.errorf(imp, "failed to import %q: %v", impPath, err) c.errorf(imp, "failed to import %q: %v", impPath, err)
return nil, false return nil, false

View file

@ -1742,9 +1742,7 @@ func (p *parser) parseImport(spread bool) *d2ast.Import {
if k.Path[0].UnquotedString != nil && len(k.Path) > 1 && k.Path[1].UnquotedString != nil && k.Path[1].Unbox().ScalarString() == "d2" { if k.Path[0].UnquotedString != nil && len(k.Path) > 1 && k.Path[1].UnquotedString != nil && k.Path[1].Unbox().ScalarString() == "d2" {
k.Path = append(k.Path[:1], k.Path[2:]...) k.Path = append(k.Path[:1], k.Path[2:]...)
} }
if k != nil { imp.Path = k.Path
imp.Path = k.Path
}
return imp return imp
} }