Debian Codegraph @

metadata/config.go

raw
1 /*
2 * config.go - Parsing for our global config file. The file is simply the JSON
3 * output of the Config protocol buffer.
4 *
5 * Copyright 2017 Google Inc.
6 * Author: Joe Richey ([email protected])
7 *
8 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
9 * use this file except in compliance with the License. You may obtain a copy of
10 * the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17 * License for the specific language governing permissions and limitations under
18 * the License.
19 */
20
21 // Package metadata contains all of the on disk structures.
22 // These structures are defined in metadata.proto. The package also
23 // contains functions for manipulating these structures, specifically:
24 // - Reading and Writing the Config file to disk
25 // - Getting and Setting Policies for directories
26 // - Reasonable defaults for a Policy's EncryptionOptions
27 package metadata
28
29 import (
30 "io"
31
32 "google.golang.org/protobuf/encoding/protojson"
33 )
34
35 // WriteConfig outputs the Config data as nicely formatted JSON
36 func WriteConfig(config *Config, out io.Writer) error {
37 m := protojson.MarshalOptions{
38 Multiline: true,
39 Indent: "\t",
40 UseProtoNames: true,
41 UseEnumNumbers: false,
42 EmitUnpopulated: true,
43 }
44 bytes, err := m.Marshal(config)
45 if err != nil {
46 return err
47 }
48 if _, err = out.Write(bytes); err != nil {
49 return err
50 }
51 _, err = out.Write([]byte{'\n'})
52 return err
53 }
54
55 // ReadConfig writes the JSON data into the config structure
56 func ReadConfig(in io.Reader) (*Config, error) {
57 bytes, err := io.ReadAll(in)
58 if err != nil {
59 return nil, err
60 }
61 config := new(Config)
62 // Discard unknown fields for forwards compatibility.
63 u := protojson.UnmarshalOptions{
64 DiscardUnknown: true,
65 }
66 return config, u.Unmarshal(bytes, config)
67 }