github.com/rck/u-root@v0.0.0-20180106144920-7eb602e381bb/cmds/ed/ed.go (about) 1 // Copyright 2012-2017 the u-root 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 // Ed is a simple line-oriented editor 6 // 7 // Synopsis: 8 // dd 9 // 10 // Description: 11 // 12 // Options: 13 package main 14 15 import ( 16 "bufio" 17 "flag" 18 "io" 19 "log" 20 "os" 21 "regexp" 22 ) 23 24 type editorArg func(Editor) error 25 26 var ( 27 d = flag.Bool("d", false, "debug") 28 debug = func(s string, i ...interface{}) {} 29 fail = log.Printf 30 f Editor = &file{} 31 num = regexp.MustCompile("^[0-9][0-9]*") 32 startsearch = regexp.MustCompile("^/[^/]/") 33 endsearch = regexp.MustCompile("^,/[^/]/") 34 editors = map[string]func(...editorArg) (Editor, error){ 35 "text": NewTextEditor, 36 "bin": NewBinEditor, 37 } 38 fileType = flag.String("t", "text", "type of file") 39 ) 40 41 func readerio(r io.Reader) editorArg { 42 return func(f Editor) error { 43 _, err := f.Read(r, 0, 0) 44 return err 45 } 46 } 47 48 func readFile(n string) editorArg { 49 return func(f Editor) error { 50 r, err := os.Open(n) 51 if err != nil { 52 return err 53 } 54 if _, err := f.Read(r, 0, 0); err != nil { 55 return err 56 } 57 return nil 58 } 59 } 60 61 func main() { 62 var ( 63 args []editorArg 64 err error 65 ) 66 67 flag.Parse() 68 69 if *d { 70 debug = log.Printf 71 } 72 73 e, ok := editors[*fileType] 74 if !ok { 75 flag.Usage() 76 } 77 78 if len(flag.Args()) == 1 { 79 args = append(args, readFile(flag.Args()[0])) 80 } 81 82 ed, err := e(args...) 83 if err != nil { 84 log.Fatalf("%v", err) 85 } 86 87 // Now just eat the lines, and turn them into commands. 88 // The format is a regular language. 89 // [start][,end]command[rest of line] 90 s := bufio.NewScanner(os.Stdin) 91 92 for s.Scan() { 93 if err := DoCommand(ed, s.Text()); err != nil { 94 log.Printf(err.Error()) 95 } 96 } 97 }