github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/cmd/generates/sources/env.go (about)

     1  /*
     2   * Copyright 2023 Wang Min Xiang
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   * 	http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   *
    16   */
    17  
    18  package sources
    19  
    20  import (
    21  	"github.com/aacfactory/errors"
    22  	"github.com/aacfactory/fns/cmd/generates/files"
    23  	"os"
    24  	"path/filepath"
    25  	"strings"
    26  )
    27  
    28  func GOPATH() (gopath string, has bool) {
    29  	gopath, has = os.LookupEnv("GOPATH")
    30  	if has {
    31  		gopath = strings.TrimSpace(gopath)
    32  		has = gopath != ""
    33  	}
    34  	return
    35  }
    36  
    37  func GOROOT() (goroot string, has bool) {
    38  	goroot, has = os.LookupEnv("GOROOT")
    39  	if has {
    40  		goroot = strings.TrimSpace(goroot)
    41  		has = goroot != ""
    42  	}
    43  	return
    44  }
    45  
    46  var pkgDir = ""
    47  
    48  func initPkgDir() (err error) {
    49  	gopath, hasGOPATH := GOPATH()
    50  	if hasGOPATH {
    51  		pkgDir = filepath.ToSlash(filepath.Join(gopath, "pkg/mod"))
    52  		if !files.ExistFile(pkgDir) {
    53  			pkgDir = ""
    54  			err = errors.Warning("sources: GOPATH was found but no 'pkg/mod' dir")
    55  			return
    56  		}
    57  		return
    58  	}
    59  	goroot, hasGOROOT := GOROOT()
    60  	if hasGOROOT {
    61  		pkgDir = filepath.ToSlash(filepath.Join(goroot, "pkg/mod"))
    62  		if !files.ExistFile(pkgDir) {
    63  			pkgDir = ""
    64  			err = errors.Warning("sources: GOROOT was found but no 'pkg/mod' dir")
    65  			return
    66  		}
    67  		return
    68  	}
    69  	if !hasGOPATH && !hasGOROOT {
    70  		err = errors.Warning("sources: GOPATH and GOROOT were not found")
    71  		return
    72  	}
    73  	return
    74  }
    75  
    76  func PKG() (pkg string) {
    77  	pkg = pkgDir
    78  	return
    79  }