github.com/turingchain2020/turingchain@v1.1.21/cmd/tools/tasks/create_file_from_str_template_task.go (about)

     1  /*
     2   * Copyright Turing Corp. 2018 All Rights Reserved.
     3   * Use of this source code is governed by a BSD-style
     4   * license that can be found in the LICENSE file.
     5   */
     6  
     7  package tasks
     8  
     9  import (
    10  	"fmt"
    11  	"strings"
    12  
    13  	"github.com/turingchain2020/turingchain/cmd/tools/util"
    14  )
    15  
    16  // CreateFileFromStrTemplateTask 从指定的模板字符串中创建目标文件的任务
    17  type CreateFileFromStrTemplateTask struct {
    18  	TaskBase
    19  	SourceStr       string
    20  	OutputFile      string
    21  	BlockStrBegin   string // Block会将SourceStr包含在内部
    22  	BlockStrEnd     string
    23  	ReplaceKeyPairs map[string]string
    24  	fileContent     string
    25  }
    26  
    27  //GetName 获取name
    28  func (c *CreateFileFromStrTemplateTask) GetName() string {
    29  	return "CreateFileFromStrTemplateTask"
    30  }
    31  
    32  //Execute 执行
    33  func (c *CreateFileFromStrTemplateTask) Execute() error {
    34  	if len(c.BlockStrBegin) > 0 && len(c.BlockStrEnd) > 0 {
    35  		c.SourceStr = fmt.Sprintf("%s%s%s", c.BlockStrBegin, c.SourceStr, c.BlockStrEnd)
    36  	}
    37  	c.fileContent = c.SourceStr
    38  	for key, value := range c.ReplaceKeyPairs {
    39  		c.fileContent = strings.Replace(c.fileContent, key, value, -1)
    40  	}
    41  	if err := util.MakeDir(c.OutputFile); err != nil {
    42  		return err
    43  	}
    44  	util.DeleteFile(c.OutputFile)
    45  	len, err := util.WriteStringToFile(c.OutputFile, c.fileContent)
    46  	if err == nil {
    47  		mlog.Info("Create file success.", "file", c.OutputFile, "file len", len)
    48  	} else {
    49  		mlog.Info("Create file falied.", "error", err)
    50  	}
    51  	return err
    52  }