Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add ToFile support to write the response into a file #5087

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions huaweicloud/helper/httphelper/http_helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,21 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"net/url"
"reflect"
"strconv"
"strings"

"github.com/hashicorp/go-multierror"
"github.com/hashicorp/go-uuid"
"github.com/tidwall/gjson"

"github.com/chnsz/golangsdk"
"github.com/chnsz/golangsdk/pagination"

"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/helper/filters"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils"
)

type HttpHelper struct {
Expand Down Expand Up @@ -265,6 +268,60 @@ func (c *HttpHelper) ExtractInto(to any) error {
return json.Unmarshal(c.responseBody, to)
}

func (c *HttpHelper) ToFile(dataPath, filePath string) error {
err := utils.WriteToFile(filePath, "", false)
if err != nil {
return err
}

var fileErr error
count := 0
err = c.EachPage(func(jsonData *gjson.Result, err error) bool {
if err != nil {
fileErr = err
return true
}

arr := jsonData.Get(dataPath).Array()
for _, v := range arr {
if err := utils.WriteToFile(filePath, fmt.Sprintf("%s\n", v.Raw), true); err != nil {
log.Printf("[ERROR] unable to write file: %s, error: %s", filePath, err)
count++
fileErr = fmt.Errorf("%v items that failed to be written to the file %s", count, err)
}
}
return true
})

mErr := multierror.Append(nil, err, fileErr)
return mErr.ErrorOrNil()
}

func (c *HttpHelper) EachPage(handler func(*gjson.Result, error) bool) error {
if c.method == "" {
c.result.Err = fmt.Errorf("`method` is empty, please specify the client through Client(method string)")
}
if c.result.Err != nil {
return c.result.Err
}

if c.pager == nil {
return fmt.Errorf("`EachPage` only supports paginated query data")
}

c.buildURL()
c.appendQueryParams()

pager := pagination.NewPager(c.client, c.url, c.pager)
pager.Headers = c.requestOpts.MoreHeaders

return pager.EachPage(func(page pagination.Page) (bool, error) {
jsonData, err := bodyToGJson(page.GetBody())
b := handler(jsonData, err)
return b, nil
})
}

func (c *HttpHelper) requestWithPage() {
body := make(map[string]any)
pager := pagination.NewPager(c.client, c.url, c.pager)
Expand Down
58 changes: 58 additions & 0 deletions huaweicloud/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -556,3 +556,61 @@ func IsUUID(uuid string) bool {
match, _ := regexp.MatchString(pattern, uuid)
return match
}

func mkdirParentDir(filePath string) error {
filePath = strings.ReplaceAll(filePath, "\\", "/")
pos := strings.LastIndexByte(filePath, '/')
if pos == -1 {
return nil
}
directory := filePath[:pos]

if err := os.MkdirAll(directory, os.ModePerm); err != nil && !os.IsExist(err) {
return fmt.Errorf("failed to create directory: %s, error: %s", directory, err)
}
return nil
}

func WriteToFile(path, content string, append bool) error {
if err := mkdirParentDir(path); err != nil {
return err
}

_, err := os.Stat(path)
if os.IsNotExist(err) {
file, err := os.Create(path)
if err != nil {
return fmt.Errorf("failed to create file: %s, error: %s", path, err)
}
defer file.Close()

_, err = file.WriteString(content)
if err != nil {
return fmt.Errorf("failed to write data to %s, error: %s", path, err)
}
return nil
}
if err != nil {
return fmt.Errorf("failed to stat file: %s, error: %s", path, err)
}

var file *os.File
if append {
file, err = os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("failed to open file for appending: %s, error: %s", path, err)
}
} else {
file, err = os.OpenFile(path, os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("failed to open file for overwriting: %s, error: %s", path, err)
}
}
defer file.Close()

_, err = file.WriteString(content)
if err != nil {
return fmt.Errorf("failed to write data to %s, error: %s", path, err)
}
return nil
}
Loading