github.com/google/yamlfmt@v0.12.2-0.20240514121411-7f77800e2681/internal/tempfile/path.go (about)

     1  // Copyright 2024 Google LLC
     2  //
     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  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package tempfile
    16  
    17  import (
    18  	"io/fs"
    19  	"os"
    20  	"path/filepath"
    21  
    22  	"github.com/google/yamlfmt/internal/collections"
    23  )
    24  
    25  type Path struct {
    26  	BasePath string
    27  	FileName string
    28  	IsDir    bool
    29  	Content  []byte
    30  }
    31  
    32  func (p *Path) Create() error {
    33  	file := p.fullPath()
    34  	var err error
    35  	if p.IsDir {
    36  		err = os.Mkdir(file, os.ModePerm)
    37  	} else {
    38  		err = os.WriteFile(file, p.Content, os.ModePerm)
    39  	}
    40  	return err
    41  }
    42  
    43  func (p *Path) fullPath() string {
    44  	return filepath.Join(p.BasePath, p.FileName)
    45  }
    46  
    47  type Paths []Path
    48  
    49  func (ps Paths) CreateAll() error {
    50  	errs := collections.Errors{}
    51  	for _, path := range ps {
    52  		errs = append(errs, path.Create())
    53  	}
    54  	return errs.Combine()
    55  }
    56  
    57  func ReplicateDirectory(dir string, newBase string) (Paths, error) {
    58  	paths := Paths{}
    59  	walkAllButCurrentDirectory := func(path string, info fs.FileInfo, walkErr error) error {
    60  		if walkErr != nil {
    61  			return walkErr
    62  		}
    63  		// Skip the current directory (basically the . directory)
    64  		if path == dir {
    65  			return nil
    66  		}
    67  		content := []byte{}
    68  
    69  		if !info.IsDir() {
    70  			readContent, err := os.ReadFile(path)
    71  			if err != nil {
    72  				return err
    73  			}
    74  			content = readContent
    75  		}
    76  
    77  		paths = append(paths, Path{
    78  			BasePath: newBase,
    79  			FileName: info.Name(),
    80  			IsDir:    info.IsDir(),
    81  			Content:  content,
    82  		})
    83  		return nil
    84  	}
    85  	err := filepath.Walk(dir, walkAllButCurrentDirectory)
    86  	return paths, err
    87  }