github.com/joomcode/cue@v0.4.4-0.20221111115225-539fe3512047/internal/ci/updatetxtar/main.go (about) 1 // Copyright 2021 The CUE Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package main 16 17 import ( 18 "flag" 19 "io" 20 "io/ioutil" 21 "log" 22 "os" 23 24 "github.com/rogpeppe/go-internal/txtar" 25 ) 26 27 // Usage: 28 // updateTxtar source target filename 29 // 30 // updateTxtar writes the contents of source (could be - for stdin) to a file 31 // (identified by filename) within the txtar archive at target. 32 33 func main() { 34 log.SetFlags(0) 35 flag.Parse() 36 if flag.NArg() != 3 { 37 log.Fatal("Usage:\n\tupdateTxtar source target filename") 38 } 39 source := flag.Arg(0) 40 target := flag.Arg(1) 41 fn := flag.Arg(2) 42 a, err := txtar.ParseFile(target) 43 if err != nil { 44 log.Fatal(err) 45 } 46 var file *txtar.File 47 for i, f := range a.Files { 48 if f.Name == fn { 49 file = &a.Files[i] 50 break 51 } 52 } 53 if file == nil { 54 a.Files = append(a.Files, txtar.File{Name: fn}) 55 file = &a.Files[len(a.Files)-1] 56 } 57 var sourceReader io.Reader 58 if source == "-" { 59 sourceReader = os.Stdin 60 } else { 61 sourceReader, err = os.Open(source) 62 if err != nil { 63 log.Fatal(err) 64 } 65 } 66 contents, err := ioutil.ReadAll(sourceReader) 67 if err != nil { 68 log.Fatal(err) 69 } 70 file.Data = contents 71 if err := ioutil.WriteFile(target, txtar.Format(a), 0666); err != nil { 72 log.Fatal(err) 73 } 74 }