~howeyc/util-windows

71f6ad100db5062ca16a922fc6d3e582e672ff8e — Chris Howey 9 months ago 8b0a9e7 master v0.4.0
tail command
2 files changed, 63 insertions(+), 1 deletions(-)

A cmd/tail/main.go
M go.mod
A cmd/tail/main.go => cmd/tail/main.go +62 -0
@@ 0,0 1,62 @@
package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"os"
)

func main() {
	var verbose, silent bool
	var linecount int
	flag.BoolVar(&verbose, "v", false, "always print file headers")
	flag.BoolVar(&silent, "q", false, "never print file headers")
	flag.IntVar(&linecount, "n", 10, "print the last `NUM` lines")
	flag.Parse()

	if linecount == 0 {
		os.Exit(0)
	}

	doTail := func(r io.Reader) {
		lineBuffer := make([]string, linecount)
		var lc, iIdx int
		scanner := bufio.NewScanner(r)
		for scanner.Scan() {
			lineBuffer[iIdx] = scanner.Text()
			iIdx++
			lc++

			if iIdx == linecount {
				iIdx = 0
			}
		}

		for lrem := min(lc, linecount); lrem > 0; lrem-- {
			i := iIdx - lrem
			if i < 0 {
				i += linecount
			}
			fmt.Println(lineBuffer[i])
		}
	}

	if flag.NArg() > 0 {
		for _, fname := range flag.Args() {
			if verbose || (!silent && flag.NArg() > 1) {
				fmt.Printf("==> %s <==\n", fname)
			}
			ifile, ierr := os.Open(fname)
			if ierr != nil {
				fmt.Fprintln(os.Stderr, ierr.Error())
				os.Exit(1)
			}
			doTail(ifile)
			ifile.Close()
		}
	} else {
		doTail(os.Stdin)
	}
}

M go.mod => go.mod +1 -1
@@ 1,6 1,6 @@
module git.sr.ht/~howeyc/util-windows

go 1.20
go 1.21

require (
	github.com/fatih/color v1.15.0