gopkg.in/ubuntu-core/snappy.v0@v0.0.0-20210902073436-25a8614f10a6/bootloader/androidbootenv/androidbootenv.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2017 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package androidbootenv
    21  
    22  import (
    23  	"bufio"
    24  	"bytes"
    25  	"fmt"
    26  	"os"
    27  	"strings"
    28  
    29  	"github.com/snapcore/snapd/logger"
    30  	"github.com/snapcore/snapd/osutil"
    31  )
    32  
    33  type Env struct {
    34  	// Map with key-value strings
    35  	env map[string]string
    36  	// File for environment storage
    37  	path string
    38  }
    39  
    40  func NewEnv(path string) *Env {
    41  	return &Env{
    42  		env:  make(map[string]string),
    43  		path: path,
    44  	}
    45  }
    46  
    47  func (a *Env) Get(name string) string {
    48  	return a.env[name]
    49  }
    50  
    51  func (a *Env) Set(key, value string) {
    52  	a.env[key] = value
    53  }
    54  
    55  func (a *Env) Load() error {
    56  	file, err := os.Open(a.path)
    57  	if err != nil {
    58  		return err
    59  	}
    60  	defer file.Close()
    61  
    62  	scanner := bufio.NewScanner(file)
    63  	for scanner.Scan() {
    64  		l := strings.SplitN(scanner.Text(), "=", 2)
    65  		// be liberal in what you accept
    66  		if len(l) < 2 {
    67  			logger.Noticef("WARNING: bad value while parsing %v (line: %q)",
    68  				a.path, scanner.Text())
    69  			continue
    70  		}
    71  		a.env[l[0]] = l[1]
    72  	}
    73  	if err := scanner.Err(); err != nil {
    74  		return err
    75  	}
    76  
    77  	return nil
    78  }
    79  
    80  func (a *Env) Save() error {
    81  	var w bytes.Buffer
    82  
    83  	for k, v := range a.env {
    84  		if _, err := fmt.Fprintf(&w, "%s=%s\n", k, v); err != nil {
    85  			return err
    86  		}
    87  	}
    88  
    89  	return osutil.AtomicWriteFile(a.path, w.Bytes(), 0644, 0)
    90  }