1 // Read and write the state file used to keep data over multiple runs
3 // Copyright (C) 2019 Simon Ruderich
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU Affero General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
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 Affero General Public License for more details.
15 // You should have received a copy of the GNU Affero General Public License
16 // along with this program. If not, see <https://www.gnu.org/licenses/>.
30 LastModified map[string]time.Time
32 // Copy of LastModified to write the state file only on changes
33 origLastModified map[string]time.Time
36 func LoadState(path string) (*State, error) {
39 x, err := ioutil.ReadFile(path)
41 // It's fine if the state file does not exist yet, we'll
42 // create it later when writing the state
43 if !os.IsNotExist(err) {
47 err := json.Unmarshal(x, &state)
53 if state.LastModified == nil {
54 state.LastModified = make(map[string]time.Time)
57 state.origLastModified = make(map[string]time.Time)
58 for k, v := range state.LastModified {
59 state.origLastModified[k] = v
65 func WriteStateIfChanged(path string, state *State) error {
66 // State hasn't changed, nothing to do
67 if reflect.DeepEqual(state.LastModified, state.origLastModified) {
71 x, err := json.Marshal(state)
76 // Write the file in an atomic fashion by creating a temporary file
77 // and renaming it over the target file
79 dir := filepath.Dir(path)
80 name := filepath.Base(path)
82 f, err := ioutil.TempFile(dir, "tmp-"+name+"-")
86 defer os.Remove(f.Name())
97 return os.Rename(f.Name(), path)