modernc.org/knuth@v0.0.4/cmd/goweave/main.go (about) 1 // Copyright 2023 The Knuth Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Command goweave is the WEAVE program by D. E. Knuth, transpiled to Go. 6 // 7 // http://mirrors.ctan.org/systems/knuth/dist/web/weave.web 8 // 9 // For more details about the original Pascal program and its usage please see 10 // the modernc.org/knuth/weave package. 11 package main // modernc.org/knuth/cmd/goweave 12 13 import ( 14 "bytes" 15 "flag" 16 "fmt" 17 "io" 18 "os" 19 "path/filepath" 20 21 "modernc.org/knuth/weave" 22 ) 23 24 func fail(rc int, s string, args ...interface{}) { 25 fmt.Fprintf(os.Stderr, s, args...) 26 os.Exit(rc) 27 } 28 29 // program WEAVE( web_file, change_file, tex_file); 30 // web_file:text_file; {primary input} 31 // change_file:text_file; {updates} 32 // tex_file: text_file; 33 34 // Main executes the weave program using the supplied arguments. 35 func main() { 36 flag.Parse() 37 nArg := flag.NArg() 38 if nArg < 1 || nArg > 3 { 39 fail(2, "expected 1 to 3 argument(s): web_file.web [change_file.ch] [tex_file.tex]\n") 40 } 41 42 args := flag.Args() 43 root := args[0] 44 root = root[:len(root)-len(filepath.Ext(root))] 45 webFile, err := os.Open(args[0]) 46 args = args[1:] 47 if err != nil { 48 fail(1, "%s\n", err) 49 } 50 51 defer webFile.Close() 52 53 changeFile := io.Reader(bytes.NewBuffer(nil)) 54 if len(args) != 0 { 55 if filepath.Ext(filepath.Base(args[0])) == ".ch" { 56 changeFile, err = os.Open(args[0]) 57 args = args[1:] 58 if err != nil { 59 fail(1, "%s\n", err) 60 } 61 } 62 } 63 64 texNm := root + ".tex" 65 if len(args) != 0 { 66 if filepath.Ext(filepath.Base(args[0])) == ".tex" { 67 texNm = args[0] 68 args = args[1:] 69 } 70 } 71 texFile, err := os.Create(texNm) 72 if err != nil { 73 fail(1, "%s\n", err) 74 } 75 76 if err = weave.Main(webFile, changeFile, texFile, os.Stdout, os.Stderr); err != nil { 77 fail(1, "FAIL: %s\n", err) 78 } 79 }