github.com/bazelbuild/rules_go@v0.47.2-0.20240515105122-e7ddb9ea474e/third_party/sanitize_patch_dates.go (about) 1 // Copyright 2019 The Bazel Authors. All rights reserved. 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 "bufio" 19 "fmt" 20 "log" 21 "os" 22 "regexp" 23 "strings" 24 ) 25 26 func main() { 27 log.SetFlags(0) 28 log.SetPrefix("sanitize_patch_dates: ") 29 if len(os.Args) == 1 { 30 log.Fatalf("usage: sanitize_patch_dates *.patch") 31 } 32 for _, arg := range os.Args[1:] { 33 if err := sanitize(arg); err != nil { 34 log.Fatal(err) 35 } 36 } 37 } 38 39 var dateRegexp = regexp.MustCompile("20..-..-.. .*") 40 41 func sanitize(filename string) (err error) { 42 r, err := os.Open(filename) 43 if err != nil { 44 return err 45 } 46 defer r.Close() 47 48 tempFilename := filename + "~" 49 w, err := os.Create(tempFilename) 50 if err != nil { 51 return err 52 } 53 defer func() { 54 if w == nil { 55 return 56 } 57 if cerr := w.Close(); err == nil && cerr != nil { 58 err = cerr 59 } 60 }() 61 62 s := bufio.NewScanner(r) 63 for s.Scan() { 64 line := s.Text() 65 if strings.HasPrefix(line, "+++") || strings.HasPrefix(line, "---") { 66 line = dateRegexp.ReplaceAllLiteralString(line, "2000-01-01 00:00:00.000000000 -0000") 67 } 68 if _, err := fmt.Fprintln(w, line); err != nil { 69 return err 70 } 71 } 72 if err := s.Err(); err != nil { 73 return err 74 } 75 76 if err := w.Close(); err != nil { 77 return err 78 } 79 w = nil 80 if err := os.Rename(tempFilename, filename); err != nil { 81 return err 82 } 83 return nil 84 }