github.com/nats-io/nsc@v0.0.0-20221206222106-35db9400b257/home/home.go (about)

     1  /*
     2   * Copyright 2018-2022 The NATS Authors
     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  
    16  package home
    17  
    18  import (
    19  	"os"
    20  	"path/filepath"
    21  
    22  	"github.com/mitchellh/go-homedir"
    23  )
    24  
    25  const StoresSubDirName = "stores"
    26  const KeysSubDirName = "keys"
    27  
    28  var home, _ = homedir.Dir()
    29  var config = envOrValue("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
    30  var data = envOrValue("XDG_DATA_HOME", filepath.Join(home, ".local", "share"))
    31  
    32  func envOrValue(name, value string) string {
    33  	ev := os.Getenv(name)
    34  	if ev != "" {
    35  		return ev
    36  	}
    37  	return value
    38  }
    39  
    40  func exists(fp string) bool {
    41  	if _, err := os.Stat(fp); err == nil {
    42  		return true
    43  	}
    44  	return false
    45  }
    46  
    47  func configHome() string {
    48  	return filepath.Join(config, "nats", "nsc")
    49  }
    50  
    51  func dataHome(dir string) string {
    52  	return filepath.Join(data, "nats", "nsc", dir)
    53  }
    54  
    55  func hasNewConfigFile() bool {
    56  	return exists(filepath.Join(configHome(), "nsc.json"))
    57  }
    58  
    59  func oldConfigDir() string {
    60  	return filepath.Join(home, ".nsc")
    61  }
    62  
    63  func hasOldConfigFile() bool {
    64  	return exists(filepath.Join(oldConfigDir(), "nsc.json"))
    65  }
    66  
    67  func hasNewDataDir(dir string) bool {
    68  	return exists(dataHome(dir))
    69  }
    70  
    71  func oldDataDir(dir string) string {
    72  	if dir == KeysSubDirName {
    73  		return filepath.Join(home, ".nkeys")
    74  	}
    75  	return filepath.Join(home, ".nsc", "nats")
    76  }
    77  
    78  func hasOldDataDir(dir string) bool {
    79  	return exists(oldDataDir(dir))
    80  }
    81  
    82  func NscConfigHome() string {
    83  	if !hasNewConfigFile() && hasOldConfigFile() {
    84  		return oldConfigDir()
    85  	}
    86  	return filepath.Join(config, "nats", "nsc")
    87  }
    88  
    89  func NscDataHome(dir string) string {
    90  	if !hasNewDataDir(dir) && hasOldDataDir(dir) {
    91  		return oldDataDir(dir)
    92  	}
    93  	return dataHome(dir)
    94  }