github.com/v2fly/tools@v0.100.0/internal/lsp/mod/format.go (about)

     1  // Copyright 2020 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 mod
     6  
     7  import (
     8  	"context"
     9  
    10  	"github.com/v2fly/tools/internal/event"
    11  	"github.com/v2fly/tools/internal/lsp/protocol"
    12  	"github.com/v2fly/tools/internal/lsp/source"
    13  )
    14  
    15  func Format(ctx context.Context, snapshot source.Snapshot, fh source.FileHandle) ([]protocol.TextEdit, error) {
    16  	ctx, done := event.Start(ctx, "mod.Format")
    17  	defer done()
    18  
    19  	pm, err := snapshot.ParseMod(ctx, fh)
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  	formatted, err := pm.File.Format()
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  	// Calculate the edits to be made due to the change.
    28  	diff, err := snapshot.View().Options().ComputeEdits(fh.URI(), string(pm.Mapper.Content), string(formatted))
    29  	if err != nil {
    30  		return nil, err
    31  	}
    32  	return source.ToProtocolEdits(pm.Mapper, diff)
    33  }