github.com/ezbuy/gauge@v0.9.4-0.20171013092048-7ac5bd3931cd/util/fileUtils.go (about)

     1  // Copyright 2015 ThoughtWorks, Inc.
     2  
     3  // This file is part of Gauge.
     4  
     5  // Gauge is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  
    10  // Gauge is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13  // GNU General Public License for more details.
    14  
    15  // You should have received a copy of the GNU General Public License
    16  // along with Gauge.  If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package util
    19  
    20  import (
    21  	"os"
    22  	"path/filepath"
    23  	"strings"
    24  
    25  	"github.com/getgauge/common"
    26  	"github.com/getgauge/gauge/config"
    27  	"github.com/getgauge/gauge/env"
    28  	"github.com/getgauge/gauge/logger"
    29  )
    30  
    31  const (
    32  	gaugeExcludeDirectories = "gauge_exclude_dirs"
    33  )
    34  
    35  func init() {
    36  	AcceptedExtensions[".spec"] = true
    37  	AcceptedExtensions[".md"] = true
    38  }
    39  
    40  // AcceptedExtensions has all the file extensions that are supported by Gauge for its specs
    41  var AcceptedExtensions = make(map[string]bool)
    42  var ignoredDirectories = make(map[string]bool)
    43  
    44  func add(value string) {
    45  	value = strings.TrimSpace(value)
    46  	if !filepath.IsAbs(value) {
    47  		path, err := filepath.Abs(filepath.Join(config.ProjectRoot, value))
    48  		if err != nil {
    49  			logger.Errorf("Error getting absolute path. %v", err)
    50  			return
    51  		}
    52  		value = path
    53  	}
    54  	ignoredDirectories[value] = true
    55  }
    56  
    57  func addDirectories(value string) {
    58  	for _, dir := range strings.Split(value, ",") {
    59  		add(dir)
    60  	}
    61  }
    62  
    63  func addIgnoredDirectories() {
    64  	ignoredDirectories[filepath.Join(config.ProjectRoot, "gauge_bin")] = true
    65  	ignoredDirectories[filepath.Join(config.ProjectRoot, "reports")] = true
    66  	ignoredDirectories[filepath.Join(config.ProjectRoot, "logs")] = true
    67  	ignoredDirectories[filepath.Join(config.ProjectRoot, common.EnvDirectoryName)] = true
    68  	addDirFromEnv(env.GaugeReportsDir, add)
    69  	addDirFromEnv(env.LogsDirectory, add)
    70  	addDirFromEnv(gaugeExcludeDirectories, addDirectories)
    71  }
    72  
    73  func addDirFromEnv(name string, add func(value string)) {
    74  	value := os.Getenv(name)
    75  	if value != "" {
    76  		add(value)
    77  	}
    78  }
    79  
    80  // findFilesIn Finds all the files in the directory of a given extension
    81  func findFilesIn(dirRoot string, isValidFile func(path string) bool, shouldSkip func(path string, f os.FileInfo) bool) []string {
    82  	absRoot, _ := filepath.Abs(dirRoot)
    83  	files := common.FindFilesInDir(absRoot, isValidFile, shouldSkip)
    84  	return files
    85  }
    86  
    87  // FindSpecFilesIn Finds spec files in the given directory
    88  func FindSpecFilesIn(dir string) []string {
    89  	return findFilesIn(dir, IsValidSpecExtension, func(path string, f os.FileInfo) bool {
    90  		return false
    91  	})
    92  }
    93  
    94  // IsValidSpecExtension Checks if the path has a spec file extension
    95  func IsValidSpecExtension(path string) bool {
    96  	return AcceptedExtensions[filepath.Ext(path)]
    97  }
    98  
    99  // FindConceptFilesIn Finds the concept files in specified directory
   100  func FindConceptFilesIn(dir string) []string {
   101  	addIgnoredDirectories()
   102  	return findFilesIn(dir, IsValidConceptExtension, func(path string, f os.FileInfo) bool {
   103  		if !f.IsDir() {
   104  			return false
   105  		}
   106  		_, ok := ignoredDirectories[path]
   107  		return strings.HasPrefix(f.Name(), ".") || ok
   108  	})
   109  }
   110  
   111  // IsValidConceptExtension Checks if the path has a concept file extension
   112  func IsValidConceptExtension(path string) bool {
   113  	return filepath.Ext(path) == ".cpt"
   114  }
   115  
   116  // IsConcept Returns true if concept file
   117  func IsConcept(path string) bool {
   118  	return IsValidConceptExtension(path)
   119  }
   120  
   121  // IsSpec Returns true if spec file file
   122  func IsSpec(path string) bool {
   123  	return IsValidSpecExtension(path)
   124  }
   125  
   126  // FindAllNestedDirs returns list of all nested directories in given path
   127  func FindAllNestedDirs(dir string) []string {
   128  	var nestedDirs []string
   129  	filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
   130  		if err == nil && info.IsDir() && !(path == dir) {
   131  			nestedDirs = append(nestedDirs, path)
   132  		}
   133  		return nil
   134  	})
   135  	return nestedDirs
   136  }
   137  
   138  // IsDir reports whether path describes a directory.
   139  func IsDir(path string) bool {
   140  	fileInfo, err := os.Stat(path)
   141  	if err != nil {
   142  		return false
   143  	}
   144  	return fileInfo.IsDir()
   145  }
   146  
   147  // GetSpecFiles returns the list of spec files present at the given path.
   148  // If the path itself represents a spec file, it returns the same.
   149  func GetSpecFiles(path string) []string {
   150  	var specFiles []string
   151  	if common.DirExists(path) {
   152  		specFiles = append(specFiles, FindSpecFilesIn(path)...)
   153  	} else if common.FileExists(path) && IsValidSpecExtension(path) {
   154  		f, _ := filepath.Abs(path)
   155  		specFiles = append(specFiles, f)
   156  	}
   157  	return specFiles
   158  }
   159  
   160  // GetConceptFiles returns the list of concept files present in the PROJECTROOT
   161  func GetConceptFiles() []string {
   162  	projRoot := config.ProjectRoot
   163  	if projRoot == "" {
   164  		logger.Fatalf("Failed to get project root.")
   165  	}
   166  	absPath, err := filepath.Abs(projRoot)
   167  	if err != nil {
   168  		logger.Fatalf("Error getting absolute path. %v", err)
   169  	}
   170  	return FindConceptFilesIn(absPath)
   171  }
   172  
   173  // SaveFile saves contents at the given path
   174  func SaveFile(fileName string, content string, backup bool) {
   175  	err := common.SaveFile(fileName, content, backup)
   176  	if err != nil {
   177  		logger.Errorf("Failed to refactor '%s': %s\n", fileName, err.Error())
   178  	}
   179  }
   180  
   181  func RelPathToProjectRoot(path string) string {
   182  	return strings.TrimPrefix(path, config.ProjectRoot+string(filepath.Separator))
   183  }
   184  
   185  // GetPathToFile returns the path to a given file from the Project root
   186  func GetPathToFile(path string) string {
   187  	if filepath.IsAbs(path) {
   188  		return path
   189  	}
   190  	return filepath.Join(config.ProjectRoot, path)
   191  }
   192  
   193  // Remove removes all the files and directories recursively for the given path
   194  func Remove(dir string) {
   195  	err := common.Remove(dir)
   196  	if err != nil {
   197  		logger.Warningf("Failed to remove directory %s. Remove it manually. %s", dir, err.Error())
   198  	}
   199  }
   200  
   201  // RemoveTempDir removes the temp dir
   202  func RemoveTempDir() {
   203  	Remove(common.GetTempDir())
   204  }