Source file src/simd/archsimd/_gen/sgutil/formatted_files.go

     1  // Copyright 2026 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 sgutil
     6  
     7  import (
     8  	"bufio"
     9  	"bytes"
    10  	"fmt"
    11  	"go/format"
    12  	"os"
    13  	"path/filepath"
    14  )
    15  
    16  func CreatePath(newFile string) (*os.File, error) {
    17  	dir := filepath.Dir(newFile)
    18  	err := os.MkdirAll(dir, 0755)
    19  	if err != nil {
    20  		return nil, fmt.Errorf("failed to create directory %s: %w", dir, err)
    21  	}
    22  	f, err := os.Create(newFile)
    23  	if err != nil {
    24  		return nil, fmt.Errorf("failed to create file %s: %w", newFile, err)
    25  	}
    26  	return f, nil
    27  }
    28  
    29  // FormatWriteAndClose formats the Go source code in source and writes it
    30  // to newFile.  If there is a problem with the formatting, the
    31  // entire source is numbered and emitted along with the error message,
    32  // to help figure out where the source code generation went wrong.
    33  func FormatWriteAndClose(source *bytes.Buffer, newFile string) {
    34  	b, err := format.Source(source.Bytes())
    35  	if err != nil {
    36  		fmt.Fprintf(os.Stderr, "%v\n", err)
    37  		fmt.Fprintf(os.Stderr, "%s\n", NumberLines(source.Bytes()))
    38  		fmt.Fprintf(os.Stderr, "%v\n", err)
    39  		panic(err)
    40  	} else {
    41  		WriteAndClose(b, newFile)
    42  	}
    43  }
    44  
    45  // WriteAndClose creates newFile, writes g to it,
    46  // and closes the file.
    47  func WriteAndClose(b []byte, newFile string) {
    48  	ofile, err := CreatePath(newFile)
    49  	if err != nil {
    50  		panic(err)
    51  	}
    52  	ofile.Write(b)
    53  	ofile.Close()
    54  }
    55  
    56  // NumberLines takes a slice of bytes, and returns a string where each line
    57  // is numbered, starting from 1.
    58  func NumberLines(data []byte) string {
    59  	var buf bytes.Buffer
    60  	r := bytes.NewReader(data)
    61  	s := bufio.NewScanner(r)
    62  	for i := 1; s.Scan(); i++ {
    63  		fmt.Fprintf(&buf, "%d: %s\n", i, s.Text())
    64  	}
    65  	return buf.String()
    66  }
    67  

View as plain text