github.com/hugh712/snapd@v0.0.0-20200910133618-1a99902bd583/overlord/devicestate/internal/state.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2019 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 internal (of devicestate) provides functions to access and
    21  // set the device state for use only by devicestate, for convenience they
    22  // are also exposed via devicestatetest for use in tests.
    23  package internal
    24  
    25  import (
    26  	"github.com/snapcore/snapd/overlord/auth"
    27  	"github.com/snapcore/snapd/overlord/state"
    28  )
    29  
    30  // Device returns the device details from the state.
    31  func Device(st *state.State) (*auth.DeviceState, error) {
    32  	var authStateData auth.AuthState
    33  
    34  	err := st.Get("auth", &authStateData)
    35  	if err == state.ErrNoState {
    36  		return &auth.DeviceState{}, nil
    37  	} else if err != nil {
    38  		return nil, err
    39  	}
    40  
    41  	if authStateData.Device == nil {
    42  		return &auth.DeviceState{}, nil
    43  	}
    44  
    45  	return authStateData.Device, nil
    46  }
    47  
    48  // SetDevice updates the device details in the state.
    49  func SetDevice(st *state.State, device *auth.DeviceState) error {
    50  	var authStateData auth.AuthState
    51  
    52  	err := st.Get("auth", &authStateData)
    53  	if err == state.ErrNoState {
    54  		authStateData = auth.AuthState{}
    55  	} else if err != nil {
    56  		return err
    57  	}
    58  
    59  	authStateData.Device = device
    60  	st.Set("auth", authStateData)
    61  
    62  	return nil
    63  }