Merge pull request #2503 from alixander/handle-rel

handle relative paths for updating imports
This commit is contained in:
Alexander Wang 2025-05-01 15:54:11 -06:00 committed by GitHub
commit f43c132f93
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 72 additions and 4 deletions

View file

@ -3406,11 +3406,35 @@ func _updateImport(m *d2ast.Map, oldPath string, newPath *string) {
}
func updateImportPath(imp *d2ast.Import, newPath string) {
if len(imp.Path) > 0 {
imp.Path[0] = d2ast.MakeValueBox(d2ast.RawString(newPath, true)).StringBox()
} else {
var pre string
pathPart := newPath
for i, r := range newPath {
if r != '.' && r != '/' {
pre = newPath[:i]
pathPart = newPath[i:]
break
}
}
if pre == "" && len(newPath) > 0 && (newPath[0] == '.' || newPath[0] == '/') {
pre = newPath
pathPart = ""
}
imp.Pre = pre
if pathPart != "" {
if len(imp.Path) > 0 {
imp.Path[0] = d2ast.MakeValueBox(d2ast.RawString(pathPart, true)).StringBox()
} else {
imp.Path = []*d2ast.StringBox{
d2ast.MakeValueBox(d2ast.RawString(pathPart, true)).StringBox(),
}
}
} else if len(imp.Path) == 0 {
imp.Path = []*d2ast.StringBox{
d2ast.MakeValueBox(d2ast.RawString(newPath, true)).StringBox(),
d2ast.MakeValueBox(d2ast.RawString("", true)).StringBox(),
}
}
}

View file

@ -9819,6 +9819,50 @@ z
exp: `x: @woof/bar/baz
y: @woof/qux/quux
z
`,
},
{
name: "update_relative_import-1",
text: `x: @../meow
y
`,
path: "../meow",
newPath: go2.Pointer("../woof"),
exp: `x: @../woof
y
`,
},
{
name: "update_relative_import-2",
text: `x: @../meow
y
`,
path: "../meow",
newPath: go2.Pointer("woof"),
exp: `x: @woof
y
`,
},
{
name: "update_relative_import-3",
text: `x: @../meow
y
`,
path: "../meow",
newPath: go2.Pointer("../meow/woof"),
exp: `x: @../meow/woof
y
`,
},
{
name: "update_relative_import-4",
text: `x: @../meow
y
`,
path: "../meow",
newPath: go2.Pointer("../g/woof"),
exp: `x: @../g/woof
y
`,
},
}