file.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. Copyright 2016 The Rook Authors. All rights reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package util
  14. import (
  15. "bytes"
  16. "fmt"
  17. "os"
  18. "path/filepath"
  19. "runtime"
  20. "github.com/coreos/pkg/capnslog"
  21. "github.com/pkg/errors"
  22. )
  23. var logger = capnslog.NewPackageLogger("github.com/rook/rook", "util")
  24. func WriteFile(filePath string, contentBuffer bytes.Buffer) error {
  25. dir := filepath.Dir(filePath)
  26. if err := os.MkdirAll(dir, 0744); err != nil {
  27. return fmt.Errorf("failed to create config file directory at %s: %+v", dir, err)
  28. }
  29. if err := os.WriteFile(filePath, contentBuffer.Bytes(), 0600); err != nil {
  30. return fmt.Errorf("failed to write config file to %s: %+v", filePath, err)
  31. }
  32. return nil
  33. }
  34. func WriteFileToLog(logger *capnslog.PackageLogger, path string) {
  35. contents, err := os.ReadFile(filepath.Clean(path))
  36. if err != nil {
  37. logger.Warningf("failed to write file %s to log: %+v", path, err)
  38. return
  39. }
  40. logger.Infof("Config file %s:\n%s", path, string(contents))
  41. }
  42. // PathToProjectRoot returns the path to the root of the rook repo on the current host.
  43. // This is primarily useful for tests.
  44. func PathToProjectRoot() string {
  45. _, path, _, _ := runtime.Caller(0) // get path to current file (<root>/pkg/util/file.go)
  46. util := filepath.Dir(path) // <root>/pkg/util
  47. pkg := filepath.Dir(util) // <root>/pkg
  48. root := filepath.Dir(pkg) // <root>
  49. return root
  50. }
  51. // CreateTempFile creates a temporary file with content passed as an argument
  52. func CreateTempFile(content string) (*os.File, error) {
  53. // Generate a temp file
  54. file, err := os.CreateTemp("", "")
  55. if err != nil {
  56. return nil, errors.Wrap(err, "failed to generate temp file")
  57. }
  58. // Write content into file
  59. err = os.WriteFile(file.Name(), []byte(content), 0400)
  60. if err != nil {
  61. return nil, errors.Wrap(err, "failed to write content into file")
  62. }
  63. return file, nil
  64. }