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