golang.org/x/tools/gopls@v0.15.3/internal/work/format.go (about)

     1  // Copyright 2022 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package work
     6  
     7  import (
     8  	"context"
     9  
    10  	"golang.org/x/mod/modfile"
    11  	"golang.org/x/tools/gopls/internal/cache"
    12  	"golang.org/x/tools/gopls/internal/file"
    13  	"golang.org/x/tools/gopls/internal/protocol"
    14  	"golang.org/x/tools/internal/diff"
    15  	"golang.org/x/tools/internal/event"
    16  )
    17  
    18  func Format(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle) ([]protocol.TextEdit, error) {
    19  	ctx, done := event.Start(ctx, "work.Format")
    20  	defer done()
    21  
    22  	pw, err := snapshot.ParseWork(ctx, fh)
    23  	if err != nil {
    24  		return nil, err
    25  	}
    26  	formatted := modfile.Format(pw.File.Syntax)
    27  	// Calculate the edits to be made due to the change.
    28  	diffs := diff.Bytes(pw.Mapper.Content, formatted)
    29  	return protocol.EditsFromDiffEdits(pw.Mapper, diffs)
    30  }