forked from u-root/u-root
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ed.go
101 lines (87 loc) · 1.87 KB
/
ed.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Copyright 2012-2017 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// ED(1) Unix Programmer's Manual ED(1)
//
// NAME
// ed - text editor
//
// SYNOPSIS
// ed [ - ] [ -d ] [ name ]
//
// DESCRIPTION
// Ed is the standard text editor.
//
// OPTIONS
package main
import (
"bufio"
"flag"
"io"
"log"
"os"
"regexp"
)
type editorArg func(Editor) error
var (
d = flag.Bool("d", false, "debug")
debug = func(s string, i ...interface{}) {}
fail = log.Printf
f Editor = &file{}
num = regexp.MustCompile("^[0-9][0-9]*")
startsearch = regexp.MustCompile("^/[^/]/")
endsearch = regexp.MustCompile("^,/[^/]/")
editors = map[string]func(...editorArg) (Editor, error){
"text": NewTextEditor,
"bin": NewBinEditor,
}
fileType = flag.String("t", "text", "type of file")
)
func readerio(r io.Reader) editorArg {
return func(f Editor) error {
_, err := f.Read(r, 0, 0)
return err
}
}
func readFile(n string) editorArg {
return func(f Editor) error {
r, err := os.Open(n)
if err != nil {
return err
}
if _, err := f.Read(r, 0, 0); err != nil {
return err
}
return nil
}
}
func main() {
var (
args []editorArg
err error
)
flag.Parse()
if *d {
debug = log.Printf
}
e, ok := editors[*fileType]
if !ok {
flag.Usage()
}
if len(flag.Args()) == 1 {
args = append(args, readFile(flag.Args()[0]))
}
ed, err := e(args...)
if err != nil {
log.Fatalf("%v", err)
}
// Now just eat the lines, and turn them into commands.
// The format is a regular language.
// [start][,end]command[rest of line]
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
if err := DoCommand(ed, s.Text()); err != nil {
log.Printf(err.Error())
}
}
}