| 1 |
// Copyright 2020 The Hugo Authors. All rights reserved. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package jsconfig |
| 15 |
|
| 16 |
import ( |
| 17 |
"path/filepath" |
| 18 |
"sort" |
| 19 |
|
| 20 |
"github.com/bep/helpers/maphelpers" |
| 21 |
) |
| 22 |
|
| 23 |
// Builder builds a jsconfig.json file that, currently, is used only to assist |
| 24 |
// IntelliSense in editors. |
| 25 |
type Builder struct { |
| 26 |
sourceRoots *maphelpers.ConcurrentSet[string] |
| 27 |
} |
| 28 |
|
| 29 |
// NewBuilder creates a new Builder. |
| 30 |
func NewBuilder() *Builder { |
| 31 |
return &Builder{sourceRoots: maphelpers.NewConcurrentSet[string]()} |
| 32 |
} |
| 33 |
|
| 34 |
// Build builds a new Config with paths relative to dir. |
| 35 |
// This method is thread safe. |
| 36 |
func (b *Builder) Build(dir string) *Config { |
| 37 |
if b.sourceRoots.Len() == 0 { |
| 38 |
return nil |
| 39 |
} |
| 40 |
var roots []string |
| 41 |
for root := range b.sourceRoots.All() { |
| 42 |
if root == dir { |
| 43 |
// We need mappings for other source roots (e.g. mounted modules), but not for the current one. |
| 44 |
// See issue 15169. |
| 45 |
continue |
| 46 |
} |
| 47 |
rel, err := filepath.Rel(dir, filepath.Join(root, "*")) |
| 48 |
if err == nil { |
| 49 |
roots = append(roots, rel) |
| 50 |
} |
| 51 |
} |
| 52 |
if len(roots) == 0 { |
| 53 |
return nil |
| 54 |
} |
| 55 |
sort.Strings(roots) |
| 56 |
conf := newJSConfig() |
| 57 |
conf.CompilerOptions.Paths["*"] = roots |
| 58 |
return conf |
| 59 |
} |
| 60 |
|
| 61 |
// AddSourceRoot adds a new source root. |
| 62 |
// This method is thread safe. |
| 63 |
func (b *Builder) AddSourceRoot(root string) { |
| 64 |
b.sourceRoots.AddIfAbsent(root) |
| 65 |
} |
| 66 |
|
| 67 |
// CompilerOptions holds compilerOptions for jsonconfig.json. |
| 68 |
type CompilerOptions struct { |
| 69 |
Paths map[string][]string `json:"paths"` |
| 70 |
} |
| 71 |
|
| 72 |
// Config holds the data for jsconfig.json. |
| 73 |
type Config struct { |
| 74 |
CompilerOptions CompilerOptions `json:"compilerOptions"` |
| 75 |
} |
| 76 |
|
| 77 |
func newJSConfig() *Config { |
| 78 |
return &Config{ |
| 79 |
CompilerOptions: CompilerOptions{ |
| 80 |
Paths: make(map[string][]string), |
| 81 |
}, |
| 82 |
} |
| 83 |
} |