github.heygears.com/openimsdk/tools@v0.0.49/config/path.go (about)

     1  // Copyright © 2024 OpenIM open source community. All rights reserved.
     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 config
    16  
    17  import (
    18  	"os"
    19  	"path/filepath"
    20  
    21  	"github.com/openimsdk/tools/errs"
    22  )
    23  
    24  // PathResolver defines methods for resolving paths related to the application.
    25  type PathResolver interface {
    26  	GetDefaultConfigPath() (string, error)
    27  	GetProjectRoot() (string, error)
    28  }
    29  
    30  type defaultPathResolver struct{}
    31  
    32  // NewPathResolver creates a new instance of the default path resolver.
    33  func NewPathResolver() *defaultPathResolver {
    34  	return &defaultPathResolver{}
    35  }
    36  
    37  func (d *defaultPathResolver) GetDefaultConfigPath(relativePath string) (string, error) {
    38  	executablePath, err := os.Executable()
    39  	if err != nil {
    40  		return "", errs.WrapMsg(err, "Executable failed")
    41  	}
    42  
    43  	configPath := filepath.Join(filepath.Dir(executablePath), relativePath)
    44  	return configPath, nil
    45  }
    46  
    47  // GetProjectRoot returns the project's root directory based on the relative depth specified.
    48  // The depth parameter specifies how many levels up from the directory of the executable the project root is located.
    49  func (d *defaultPathResolver) GetProjectRoot(depth int) (string, error) {
    50  	executablePath, err := os.Executable()
    51  	if err != nil {
    52  		return "", errs.WrapMsg(err, "Executable failed")
    53  	}
    54  
    55  	// Move up the specified number of directories to find the project root
    56  	projectRoot := executablePath
    57  	for i := 0; i < depth; i++ {
    58  		projectRoot = filepath.Dir(projectRoot)
    59  	}
    60  
    61  	return projectRoot, nil
    62  }