pax_global_header00006660000000000000000000000064133144773770014532gustar00rootroot0000000000000052 comment=9b292693c55c791c79825cdce5b7e0b3b6da6e88 osrelease-0.0.1/000077500000000000000000000000001331447737700135125ustar00rootroot00000000000000osrelease-0.0.1/.gitignore000066400000000000000000000000121331447737700154730ustar00rootroot00000000000000osrelease osrelease-0.0.1/LICENSE000066400000000000000000000261351331447737700145260ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. osrelease-0.0.1/Makefile000066400000000000000000000006501331447737700151530ustar00rootroot00000000000000default: help help: @echo "- deps: Install dependencies needed by osrelease" @echo "- osrelease: Build osrelease" @echo "- clean: Clean artifacts" deps: go get -u gopkg.in/yaml.v2 go get -u github.com/spf13/cobra osrelease: go build -ldflags '-X main.version=$(shell cat VERSION) -X main.gitCommit=$(shell git rev-parse --short HEAD) -X main.buildInfo=$(shell date +%s)' -o $@ cmd/main.go clean: rm -f osrelease osrelease-0.0.1/README.md000066400000000000000000000031121331447737700147660ustar00rootroot00000000000000# osrelease - Go library/binary for parsing osrelease See the [os-release](https://www.freedesktop.org/software/systemd/man/os-release.html) documentation. ## Building ```bash make deps # Install dependencies ... make osrelease # Create the binary ... ``` ## Usage **Note**: ``OSRelease`` type directly supports fields as defined by the ``os-release`` documentation. Fields that are present but are not explicitly part of said documentation are added in ``ADDITIONAL_FIELDS``. When using the command line binary these fields are accesses the same way as supported fields. When using osrelease as a library to find unsupported fields ``ADDITIONAL_FIELDS`` (``map[string]string``) will need to be searched. ### Command Line ```bash # A single field ./osrelease field ID fedora$ # A field that is not considered part of the supported set ./osrelease field REDHAT_BUGZILLA_PRODUCT_VERSION 26$ # A field that doesn't exist $ ./osrelease field idonotexist $ echo $? 1 # In a format ./osrelease yaml name: Fedora version: 26 (Workstation Edition) id: fedora ... $ ``` ### Library ```golang import ( "errors" "github.com/ashcrow/osrelease" ) func RequireFedora() error { // The OSRelease instance using the default paths or, err := osrelease.New(nil) // Or to inspect the files in /sysroot //or, err := osrelease.NewWithOverrides("/sysroot/etc/osrelease", "/tmp/someplace/usr/lib/os-release")) // Handle the error however you see fit if err != nil { return err } if or.ID != "fedora" { return errors.New("Fedora Linux is a requirement") } // Everything is fine return nil } ``` osrelease-0.0.1/VERSION000066400000000000000000000000061331447737700145560ustar00rootroot000000000000000.0.1 osrelease-0.0.1/cmd/000077500000000000000000000000001331447737700142555ustar00rootroot00000000000000osrelease-0.0.1/cmd/main.go000066400000000000000000000050251331447737700155320ustar00rootroot00000000000000package main import ( "encoding/json" "errors" "fmt" "log" "os" "gopkg.in/yaml.v2" "github.com/ashcrow/osrelease" "github.com/spf13/cobra" ) // version of the build var version string // latest git commit in this build var gitCommit string // when the build occured var buildInfo string // main is the main entry point for executing the CLI func main() { // The OSRelease instance to use in commands or, err := osrelease.New() if err != nil { log.Fatalln(err) } // root command which doesn't do anything but show help var rootCommand = &cobra.Command{ Use: "osrelease", Short: "osrelease parses and provides osrelease data", RunE: func(cmd *cobra.Command, args []string) error { return errors.New("Please specify an output format.") }, } // The version number of this build var versionCommand = &cobra.Command{ Use: "version", Short: "Print the version number of osrelease", Run: func(cmd *cobra.Command, args []string) { fmt.Println(version) }, } // The version number of this build var buildInfoCommand = &cobra.Command{ Use: "buildinfo", Short: "Print the build information", Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Version: %s\n", version) fmt.Printf("GitCommit: %s\n", gitCommit) fmt.Printf("BuildInfo: %s\n", buildInfo) }, } // command for outputting in json var jsonCommand = &cobra.Command{ Use: "json", Short: "Parse and print the file in json format", Run: func(cmd *cobra.Command, args []string) { data, err := json.MarshalIndent(or, "", " ") if err != nil { log.Fatal(err) } fmt.Printf(string(data)) }, } // command for outputting in YAML var yamlCommand = &cobra.Command{ Use: "yaml", Short: "Parse and print the file in yaml format", Run: func(cmd *cobra.Command, args []string) { data, err := yaml.Marshal(or) if err != nil { log.Fatal(err) } fmt.Printf(string(data)) }, } // command for outputting a single field var fieldCommand = &cobra.Command{ Use: "field FIELDNAME", Short: "Parse and print a single field", Args: func(cmd *cobra.Command, args []string) error { if len(args) == 1 { return nil } return errors.New("Requires a single field to be provided") }, Run: func(cmd *cobra.Command, args []string) { data, err := or.GetField(args[0]) if err != nil { os.Exit(1) } fmt.Printf(string(data)) }, } // Add our commands rootCommand.AddCommand(versionCommand, buildInfoCommand, jsonCommand, yamlCommand, fieldCommand) // Execute rootCommand.Execute() } osrelease-0.0.1/osrelease.go000066400000000000000000000104371331447737700160300ustar00rootroot00000000000000// Package osrelease package provides access to parsed os-release information package osrelease import ( "errors" "io/ioutil" "reflect" "strings" ) // etcPath is the default path to os-release in etc var etcPath = "/etc/os-release" // usrPath is the default path to os-release in usr var usrPath = "/usr/lib/os-release" // OSRelease implements the format noted at // https://www.freedesktop.org/software/systemd/man/os-release.html type OSRelease struct { NAME string // OS Identifier VERSION string // Full OS Version ID string // Lowercase OS identifier ID_LIKE string // Coma seperated list of closely related OSes VERSION_ID string // Lowercase OS version VERSION_CODENAME string // Lowercase OS release codename PRETTY_NAME string // Human presented OS/Release name ANSI_COLOR string // Suggested color for showing OS name CPE_NAME string // See http://scap.nist.gov/specifications/cpe/ HOME_URL string // Main link for the OS BUG_REPORT_URL string // Bug report link for the OS PRIVACY_POLICY_URL string // Privacy policy link for the OS VARIANT string // Human presnted OS Variant VARIANT_ID string // Lowercase OS Variant identifier ADDITIONAL_FIELDS map[string]string // Custom/unsupported fields supportedFields []string // List of supported fields } // getFields denerates a list of fields which are supported by // the os-release spec. func (o *OSRelease) getFields() []string { t := reflect.ValueOf(OSRelease{}).Type() var fields []string for x := 0; x < t.NumField(); x++ { fields = append(fields, t.Field(x).Name) } return fields } // SetField sets a field on an instance of OSRelease. // If the field is not a supported field it will be // added to ADDITIONAL_FIELDS. func (o *OSRelease) SetField(key, value string) { supported := false for _, supportedKey := range o.supportedFields { if key == supportedKey { supported = true break } } if supported == true { field := reflect.ValueOf(o).Elem() field.FieldByName(key).SetString(value) } else { o.ADDITIONAL_FIELDS[key] = value } } // GetField returns a field from the instance. If the // field is not present then an error us returned. func (o *OSRelease) GetField(key string) (string, error) { supported := false for _, supportedKey := range o.supportedFields { if key == supportedKey { supported = true break } } if supported == true { return reflect.ValueOf(*o).FieldByName(key).String(), nil } for additionalKey := range o.ADDITIONAL_FIELDS { if key == additionalKey { return o.ADDITIONAL_FIELDS[additionalKey], nil } } // Fail case return "", errors.New("Field does not exist") } // Populate reads the os-release file, parses it, and // sets fields for use. func (o *OSRelease) Populate(paths []string) error { o.supportedFields = o.getFields() o.ADDITIONAL_FIELDS = make(map[string]string) // Iterate over our known file paths var rawContent []byte var err error for _, path := range paths { rawContent, err = ioutil.ReadFile(path) if err == nil { break } } // Error if we were unable to get any content if len(rawContent) == 0 { return errors.New("No content available from os-release files") } for _, line := range strings.Split(string(rawContent), "\n") { if strings.Contains(line, "=") { item := strings.Split(string(line), "=") // Remove prefix/suffix quotes from values item[1] = strings.TrimPrefix(item[1], "\"") item[1] = strings.TrimSuffix(item[1], "\"") // Set the field o.SetField(item[0], item[1]) } } return nil } // New creates and returns a new insance of OSRelease. // Generally New should be used to create a new instance. func New() (OSRelease, error) { o, err := NewWithOverrides(etcPath, usrPath) if err != nil { return o, err } return o, nil } // NewWithOverrides creates and returns a new instance of OSRelease // using the paths passed in. func NewWithOverrides(etcOverridePath, usrOverridePath string) (OSRelease, error) { o := OSRelease{} err := o.Populate([]string{etcOverridePath, usrOverridePath}) if err != nil { return o, err } return o, nil }