github.com/ubuntu/ubuntu-report@v1.7.4-0.20240410144652-96f37d845fac/internal/utils/reports.go (about)

     1  package utils
     2  
     3  import (
     4  	"os"
     5  	"os/user"
     6  	"path/filepath"
     7  
     8  	"github.com/pkg/errors"
     9  )
    10  
    11  const (
    12  	defaultCacheDir = ".cache"
    13  	reportDir       = "ubuntu-report"
    14  )
    15  
    16  var (
    17  	// ErrFormat used to print debug messages.
    18  	// Only for log.() msg, not errors.() error wrapping!
    19  	ErrFormat = "%v"
    20  )
    21  
    22  // ReportPath of last saved report
    23  func ReportPath(distro, version string, cacheP string) (string, error) {
    24  	if cacheP == "" {
    25  		var err error
    26  		if cacheP, err = cacheDir(); err != nil {
    27  			return "", err
    28  		}
    29  	}
    30  	return filepath.Join(cacheP, reportDir, distro+"."+version), nil
    31  }
    32  
    33  // PendingReportPath of last saved pending report
    34  func PendingReportPath(cacheP string) (string, error) {
    35  	if cacheP == "" {
    36  		var err error
    37  		if cacheP, err = cacheDir(); err != nil {
    38  			return "", err
    39  		}
    40  	}
    41  	return filepath.Join(cacheP, reportDir, "pending"), nil
    42  }
    43  
    44  func cacheDir() (string, error) {
    45  	d := os.Getenv("XDG_CACHE_HOME")
    46  	if filepath.IsAbs(d) {
    47  		return d, nil
    48  	}
    49  
    50  	if d == "" {
    51  		d = defaultCacheDir
    52  	}
    53  	h, err := getHomeDir()
    54  	if err != nil {
    55  		return "", err
    56  	}
    57  	return filepath.Join(h, d), nil
    58  }
    59  
    60  func getHomeDir() (string, error) {
    61  	d := os.Getenv("HOME")
    62  
    63  	if d == "" {
    64  		usr, err := user.Current()
    65  		if err != nil {
    66  			return "", errors.Wrapf(err, "couldn't get user home directory")
    67  		}
    68  		d = usr.HomeDir
    69  	}
    70  
    71  	return d, nil
    72  }