github.com/defang-io/defang/src@v0.0.0-20240505002154-bdf411911834/pkg/cli/generate.go (about)

     1  package cli
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os"
     7  
     8  	"github.com/defang-io/defang/src/pkg/cli/client"
     9  	"github.com/defang-io/defang/src/pkg/term"
    10  	defangv1 "github.com/defang-io/defang/src/protos/io/defang/v1"
    11  )
    12  
    13  func Generate(ctx context.Context, client client.Client, language string, description string) ([]string, error) {
    14  	if DoDryRun {
    15  		term.Warn(" ! Dry run, not generating files")
    16  		return nil, ErrDryRun
    17  	}
    18  
    19  	response, err := client.GenerateFiles(ctx, &defangv1.GenerateFilesRequest{
    20  		AgreeTos: true, // agreement was already checked by the caller
    21  		Language: language,
    22  		Prompt:   description,
    23  	})
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  
    28  	if term.DoDebug {
    29  		// Print the files that were generated
    30  		for _, file := range response.Files {
    31  			term.Debug(file.Name + "\n```")
    32  			term.Debug(file.Content)
    33  			term.Debug("```")
    34  			term.Debug("")
    35  			term.Debug("")
    36  		}
    37  	}
    38  
    39  	// Write each file to disk
    40  	term.Info(" * Writing files to disk...")
    41  	for _, file := range response.Files {
    42  		// Print the files that were generated
    43  		fmt.Println("   -", file.Name)
    44  		// TODO: this will overwrite existing files
    45  		if err = os.WriteFile(file.Name, []byte(file.Content), 0644); err != nil {
    46  			return nil, err
    47  		}
    48  	}
    49  
    50  	// put the file names in an array
    51  	var fileNames []string
    52  	for _, file := range response.Files {
    53  		fileNames = append(fileNames, file.Name)
    54  	}
    55  
    56  	return fileNames, nil
    57  }