github.com/wmuizelaar/kpt@v0.0.0-20221018115725-bd564717b2ed/mdtogo/common/common.go (about)

     1  // Copyright 2019 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 common
    16  
    17  import (
    18  	"os"
    19  	"path/filepath"
    20  )
    21  
    22  const markdownExtension = ".md"
    23  
    24  func ReadFiles(source string, recursive bool) ([]string, error) {
    25  	filePaths := make([]string, 0)
    26  	if recursive {
    27  		err := filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
    28  			if err != nil {
    29  				return err
    30  			}
    31  			if filepath.Ext(info.Name()) == markdownExtension {
    32  				filePaths = append(filePaths, path)
    33  			}
    34  			return nil
    35  		})
    36  		if err != nil {
    37  			return filePaths, err
    38  		}
    39  	} else {
    40  		if filepath.Ext(source) == markdownExtension {
    41  			filePaths = append(filePaths, source)
    42  		} else {
    43  			files, err := os.ReadDir(source)
    44  			if err != nil {
    45  				return filePaths, err
    46  			}
    47  			for _, info := range files {
    48  				if filepath.Ext(info.Name()) == markdownExtension {
    49  					path := filepath.Join(source, info.Name())
    50  					filePaths = append(filePaths, path)
    51  				}
    52  			}
    53  		}
    54  	}
    55  	return filePaths, nil
    56  }