|
| 1 | +/** |
| 2 | +# Copyright (c) NVIDIA CORPORATION. All rights reserved. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +**/ |
| 16 | + |
| 17 | +package engine |
| 18 | + |
| 19 | +import ( |
| 20 | + "fmt" |
| 21 | + "os" |
| 22 | + "path/filepath" |
| 23 | +) |
| 24 | + |
| 25 | +// Config represents a runtime config |
| 26 | +type Config string |
| 27 | + |
| 28 | +// Write writes the specified contents to a config file. |
| 29 | +func (c Config) Write(output []byte) (int, error) { |
| 30 | + path := string(c) |
| 31 | + if path == "" { |
| 32 | + n, err := os.Stdout.Write(output) |
| 33 | + if err == nil { |
| 34 | + os.Stdout.WriteString("\n") |
| 35 | + } |
| 36 | + return n, err |
| 37 | + } |
| 38 | + |
| 39 | + if len(output) == 0 { |
| 40 | + err := os.Remove(path) |
| 41 | + if err != nil { |
| 42 | + return 0, fmt.Errorf("unable to remove empty file: %v", err) |
| 43 | + } |
| 44 | + return 0, nil |
| 45 | + } |
| 46 | + |
| 47 | + if dir := filepath.Dir(path); dir != "" { |
| 48 | + err := os.MkdirAll(dir, 0755) |
| 49 | + if err != nil { |
| 50 | + return 0, fmt.Errorf("unable to create directory %v: %v", dir, err) |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + f, err := os.Create(path) |
| 55 | + if err != nil { |
| 56 | + return 0, fmt.Errorf("unable to open %v for writing: %v", path, err) |
| 57 | + } |
| 58 | + defer f.Close() |
| 59 | + |
| 60 | + return f.Write(output) |
| 61 | +} |
0 commit comments