cuelang.org/go@v0.10.1/internal/golangorgx/gopls/cuelang/format.go (about) 1 // Copyright 2024 The CUE Authors 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 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Package golang defines the LSP features for navigation, analysis, 16 // and refactoring of Go source code. 17 package cuelang 18 19 import ( 20 "bytes" 21 "context" 22 23 cueformat "cuelang.org/go/cue/format" 24 25 "cuelang.org/go/internal/golangorgx/gopls/cache" 26 "cuelang.org/go/internal/golangorgx/gopls/file" 27 "cuelang.org/go/internal/golangorgx/gopls/protocol" 28 "cuelang.org/go/internal/golangorgx/tools/diff" 29 "cuelang.org/go/internal/golangorgx/tools/event" 30 ) 31 32 // FormatCUE formats a CUE file with a given range. 33 func FormatCUE(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle) ([]protocol.TextEdit, error) { 34 ctx, done := event.Start(ctx, "source.FormatCUE") 35 defer done() 36 37 // TODO cache the parsed artefacts, which will include the mapper 38 39 src, err := fh.Content() 40 if err != nil { 41 return nil, err 42 } 43 res, err := cueformat.Source(src) 44 if err != nil { 45 // TODO fix up the AST like gopls so we can do more with 46 // partial/incomplete code. 47 // 48 // For now return early because there is nothing we can do. 49 return nil, nil 50 } 51 52 // If the format did nothing, do nothing 53 if bytes.Equal(src, res) { 54 return nil, nil 55 } 56 57 mapper := protocol.NewMapper(fh.URI(), src) 58 edits := diff.Strings(string(src), string(res)) 59 return protocol.EditsFromDiffEdits(mapper, edits) 60 }