vitess.io/vitess@v0.16.2/go/tools/goimports/goimports.go (about)

     1  /*
     2  Copyright 2021 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package goimports
    18  
    19  import (
    20  	"os"
    21  	"os/exec"
    22  
    23  	"github.com/dave/jennifer/jen"
    24  )
    25  
    26  // FormatJenFile formats the given *jen.File with goimports and return a slice
    27  // of byte corresponding to the formatted file.
    28  func FormatJenFile(file *jen.File) ([]byte, error) {
    29  	tempFile, err := os.CreateTemp("/tmp", "*.go")
    30  	if err != nil {
    31  		return nil, err
    32  	}
    33  
    34  	err = file.Save(tempFile.Name())
    35  	if err != nil {
    36  		return nil, err
    37  	}
    38  
    39  	cmd := exec.Command("goimports", "-local", "vitess.io/vitess", "-w", tempFile.Name())
    40  	cmd.Stderr = os.Stderr
    41  	err = cmd.Run()
    42  	if err != nil {
    43  		return nil, err
    44  	}
    45  	return os.ReadFile(tempFile.Name())
    46  }