github.com/opentofu/opentofu@v1.7.1/internal/command/cliconfig/config_unix.go (about)

     1  // Copyright (c) The OpenTofu Authors
     2  // SPDX-License-Identifier: MPL-2.0
     3  // Copyright (c) 2023 HashiCorp, Inc.
     4  // SPDX-License-Identifier: MPL-2.0
     5  
     6  //go:build !windows
     7  // +build !windows
     8  
     9  package cliconfig
    10  
    11  import (
    12  	"errors"
    13  	"os"
    14  	"os/user"
    15  	"path/filepath"
    16  )
    17  
    18  func configFile() (string, error) {
    19  	dir, err := homeDir()
    20  	if err != nil {
    21  		return "", err
    22  	}
    23  
    24  	newConfigFile := filepath.Join(dir, ".tofurc")
    25  	legacyConfigFile := filepath.Join(dir, ".terraformrc")
    26  
    27  	if xdgDir := os.Getenv("XDG_CONFIG_HOME"); xdgDir != "" && !pathExists(legacyConfigFile) && !pathExists(newConfigFile) {
    28  		// a fresh install should not use terraform naming
    29  		return filepath.Join(xdgDir, "opentofu", "tofurc"), nil
    30  	}
    31  
    32  	return getNewOrLegacyPath(newConfigFile, legacyConfigFile)
    33  }
    34  
    35  func configDir() (string, error) {
    36  	dir, err := homeDir()
    37  	if err != nil {
    38  		return "", err
    39  	}
    40  
    41  	configDir := filepath.Join(dir, ".terraform.d")
    42  	if xdgDir := os.Getenv("XDG_CONFIG_HOME"); !pathExists(configDir) && xdgDir != "" {
    43  		configDir = filepath.Join(xdgDir, "opentofu")
    44  	}
    45  
    46  	return configDir, nil
    47  }
    48  
    49  func dataDirs() ([]string, error) {
    50  	dir, err := homeDir()
    51  	if err != nil {
    52  		return nil, err
    53  	}
    54  
    55  	dirs := []string{filepath.Join(dir, ".terraform.d")}
    56  	if xdgDir := os.Getenv("XDG_DATA_HOME"); xdgDir != "" {
    57  		dirs = append(dirs, filepath.Join(xdgDir, "opentofu"))
    58  	}
    59  
    60  	return dirs, nil
    61  }
    62  
    63  func homeDir() (string, error) {
    64  	// First prefer the HOME environmental variable
    65  	if home := os.Getenv("HOME"); home != "" {
    66  		// FIXME: homeDir gets called from globalPluginDirs during init, before
    67  		// the logging is set up.  We should move meta initializtion outside of
    68  		// init, but in the meantime we just need to silence this output.
    69  		// log.Printf("[DEBUG] Detected home directory from env var: %s", home)
    70  
    71  		return home, nil
    72  	}
    73  
    74  	// If that fails, try build-in module
    75  	user, err := user.Current()
    76  	if err != nil {
    77  		return "", err
    78  	}
    79  
    80  	if user.HomeDir == "" {
    81  		return "", errors.New("blank output")
    82  	}
    83  
    84  	return user.HomeDir, nil
    85  }
    86  
    87  func pathExists(path string) bool {
    88  	_, err := os.Stat(path)
    89  	return err == nil
    90  }