github.com/TrueBlocks/trueblocks-core/src/apps/chifra@v0.0.0-20241022031540-b362680128f7/internal/init/handle_example.go (about)

     1  // Copyright 2021 The TrueBlocks Authors. All rights reserved.
     2  // Use of this source code is governed by a license that can
     3  // be found in the LICENSE file.
     4  
     5  package initPkg
     6  
     7  import (
     8  	"os"
     9  	"path/filepath"
    10  	"strings"
    11  
    12  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/file"
    13  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/logger"
    14  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/output"
    15  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/utils"
    16  )
    17  
    18  // HandleExample populates a subfolder of the ./examples folder with a skeleton
    19  // of the files needed to run an example. This is a convenience function for
    20  // developers to quickly get started with the example.
    21  func (opts *InitOptions) HandleExample(rCtx *output.RenderCtx) error {
    22  	template := "base/"                                  // will use opts.Template in the future
    23  	tmplFolder := filepath.Join("./templates", template) // will later support opts.Template
    24  	exampleDir := filepath.Join("./", opts.Example)
    25  
    26  	// We already know that the folder does not exist since it passed validation...
    27  	_ = os.MkdirAll(exampleDir, 0755)
    28  
    29  	logger.Info("Example created in ", filepath.Join("./", opts.Example)+" from "+tmplFolder)
    30  
    31  	for _, fn := range []string{"main.go", "main_test.go", "go.mod", "README.md"} {
    32  		copyOne(fn, opts.Example, tmplFolder)
    33  	}
    34  
    35  	// tidy
    36  	cmd := "cd " + exampleDir + " && "
    37  	cmd += "go get github.com/btcsuite/btcd && "
    38  	cmd += "go mod tidy"
    39  	utils.System(cmd)
    40  
    41  	// update the go.work file
    42  	os.Remove(filepath.Join("..", "go.work"))
    43  	utils.System("source ../scripts/go-work-sync.sh")
    44  
    45  	return nil
    46  }
    47  
    48  func copyOne(fn, exName, tmplFolder string) {
    49  	contents := file.AsciiFileToString(filepath.Join(tmplFolder, fn+".tmpl"))
    50  	contents = strings.ReplaceAll(contents, "[{NAME}]", utils.MakeFirstUpperCase(exName))
    51  	contents = strings.ReplaceAll(contents, "[{LOWER}]", exName)
    52  	fn = filepath.Join("./", exName, fn)
    53  	_ = file.StringToAsciiFile(fn, contents)
    54  	logger.Info("\t==> " + fn)
    55  }