@@ -148,12 +148,56 @@ func (py *Resolver) Resolve(
148
148
modules := modulesRaw .(* treeset.Set )
149
149
it := modules .Iterator ()
150
150
explainDependency := os .Getenv ("EXPLAIN_DEPENDENCY" )
151
+ // Resolve relative paths for package generation
152
+ isPackageGeneration := ! cfg .PerFileGeneration () && ! cfg .CoarseGrainedGeneration ()
151
153
hasFatalError := false
152
154
MODULES_LOOP:
153
155
for it .Next () {
154
156
mod := it .Value ().(module )
155
- moduleParts := strings .Split (mod .Name , "." )
156
- possibleModules := []string {mod .Name }
157
+ moduleName := mod .Name
158
+ // Transform relative imports `.` or `..foo.bar` into the package path from root.
159
+ if strings .HasPrefix (moduleName , "." ) {
160
+ // If not package generation mode, skip relative imports
161
+ if ! isPackageGeneration {
162
+ continue MODULES_LOOP
163
+ }
164
+ relativeDepth := 0
165
+ for i := 0 ; i < len (moduleName ); i ++ {
166
+ if moduleName [i ] == '.' {
167
+ relativeDepth ++
168
+ } else {
169
+ break
170
+ }
171
+ }
172
+
173
+ // Extract suffix after leading dots
174
+ relativeSuffix := moduleName [relativeDepth :]
175
+ var relativeSuffixParts []string
176
+ if relativeSuffix != "" {
177
+ relativeSuffixParts = strings .Split (relativeSuffix , "." )
178
+ }
179
+
180
+ // Split current package label into parts
181
+ pkgParts := strings .Split (from .Pkg , "/" )
182
+
183
+ if relativeDepth - 1 > len (pkgParts ) {
184
+ // Trying to go above the root
185
+ log .Printf ("ERROR: Invalid relative import %q in %q: exceeds package root." , moduleName , mod .Filepath )
186
+ continue MODULES_LOOP
187
+ }
188
+
189
+ // Go up `relativeDepth - 1` levels
190
+ baseParts := pkgParts
191
+ if relativeDepth > 1 {
192
+ baseParts = pkgParts [:len (pkgParts )- (relativeDepth - 1 )]
193
+ }
194
+
195
+ absParts := append (baseParts , relativeSuffixParts ... )
196
+ moduleName = strings .Join (absParts , "." )
197
+ }
198
+
199
+ moduleParts := strings .Split (moduleName , "." )
200
+ possibleModules := []string {moduleName }
157
201
for len (moduleParts ) > 1 {
158
202
// Iterate back through the possible imports until
159
203
// a match is found.
0 commit comments