github.com/stolowski/snapd@v0.0.0-20210407085831-115137ce5a22/snapdtool/info_file.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2019-2020 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 snapdtool
    21  
    22  import (
    23  	"bytes"
    24  	"fmt"
    25  	"io/ioutil"
    26  )
    27  
    28  // SnapdVersionFromInfoFile returns snapd version read for the
    29  // given info" file, pointed by infoPath.
    30  // The format of the "info" file is a single line with "VERSION=..."
    31  // in it. The file is produced by mkversion.sh and normally installed
    32  // along snapd binary in /usr/lib/snapd.
    33  func SnapdVersionFromInfoFile(infoPath string) (string, error) {
    34  	content, err := ioutil.ReadFile(infoPath)
    35  	if err != nil {
    36  		return "", fmt.Errorf("cannot open snapd info file %q: %s", infoPath, err)
    37  	}
    38  
    39  	if !bytes.HasPrefix(content, []byte("VERSION=")) {
    40  		idx := bytes.Index(content, []byte("\nVERSION="))
    41  		if idx < 0 {
    42  			return "", fmt.Errorf("cannot find snapd version information in %q", content)
    43  		}
    44  		content = content[idx+1:]
    45  	}
    46  	content = content[8:]
    47  	idx := bytes.IndexByte(content, '\n')
    48  	if idx > -1 {
    49  		content = content[:idx]
    50  	}
    51  
    52  	return string(content), nil
    53  }