github.com/apache/incubator-kie-tools/packages/kn-plugin-workflow@v0.28.1-0.20240311201729-34c6856b157f/pkg/common/io.go (about)

     1  /*
     2   * Licensed to the Apache Software Foundation (ASF) under one
     3   * or more contributor license agreements.  See the NOTICE file
     4   * distributed with this work for additional information
     5   * regarding copyright ownership.  The ASF licenses this file
     6   * to you under the Apache License, Version 2.0 (the
     7   * "License"); you may not use this file except in compliance
     8   * with the License.  You may obtain a copy of the License at
     9   *
    10   *  http://www.apache.org/licenses/LICENSE-2.0
    11   *
    12   * Unless required by applicable law or agreed to in writing,
    13   * software distributed under the License is distributed on an
    14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    15   * KIND, either express or implied.  See the License for the
    16   * specific language governing permissions and limitations
    17   * under the License.
    18   */
    19  
    20  package common
    21  
    22  import (
    23  	"fmt"
    24  	"io"
    25  	"os"
    26  	"path/filepath"
    27  	"strings"
    28  )
    29  
    30  func FindFilesWithExtensions(directoryPath string, extensions []string) ([]string, error) {
    31  	filePaths := []string{}
    32  
    33  	_, err := os.Stat(directoryPath)
    34  	if os.IsNotExist(err) {
    35  		return filePaths, nil
    36  	} else if err != nil {
    37  		return nil, fmt.Errorf("❌ ERROR: failed to access directory: %s", err)
    38  	}
    39  
    40  	files, err := os.ReadDir(directoryPath)
    41  	if err != nil {
    42  		return nil, fmt.Errorf("❌ ERROR: failed to read directory: %s", err)
    43  	}
    44  
    45  	for _, file := range files {
    46  		if file.IsDir() {
    47  			continue
    48  		}
    49  
    50  		filename := file.Name()
    51  		for _, ext := range extensions {
    52  			if strings.HasSuffix(strings.ToLower(filename), strings.ToLower(ext)) {
    53  				filePath := filepath.Join(directoryPath, filename)
    54  				filePaths = append(filePaths, filePath)
    55  				break
    56  			}
    57  		}
    58  	}
    59  
    60  	return filePaths, nil
    61  }
    62  
    63  func MustGetFile(filepath string) (io.Reader, error) {
    64  	file, err := os.OpenFile(filepath, os.O_RDONLY, os.ModePerm)
    65  	if err != nil {
    66  		return nil, fmt.Errorf("❌ ERROR: failed to read file: %s", err)
    67  	}
    68  	return file, nil
    69  }