github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/util/config/file.go (about)

     1  package config
     2  
     3  import (
     4  	"encoding/json"
     5  	"io/ioutil"
     6  	"os"
     7  	"path/filepath"
     8  	"time"
     9  )
    10  
    11  // Version represents ./micro/version
    12  type Version struct {
    13  	Version string    `json:"version"`
    14  	Updated time.Time `json:"updated"`
    15  }
    16  
    17  // WriteVersion will write a version update to a file ./micro/version.
    18  // This indicates the current version and the last time we updated the binary.
    19  // Its only used where self update is
    20  func WriteVersion(v string) error {
    21  	dir := filepath.Dir(File)
    22  	if err := os.MkdirAll(dir, 0755); err != nil {
    23  		return err
    24  	}
    25  	b, err := json.Marshal(&Version{
    26  		Version: v,
    27  		Updated: time.Now(),
    28  	})
    29  	if err != nil {
    30  		return err
    31  	}
    32  	f := filepath.Join(dir, "version")
    33  	return ioutil.WriteFile(f, b, 0644)
    34  }
    35  
    36  // GetVersion returns the version from .micro/version. If it does not exist
    37  func GetVersion() (*Version, error) {
    38  	dir := filepath.Dir(File)
    39  	f := filepath.Join(dir, "version")
    40  	b, err := ioutil.ReadFile(f)
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  	v := new(Version)
    45  	if err := json.Unmarshal(b, &v); err != nil {
    46  		return nil, err
    47  	}
    48  	return v, nil
    49  }