~howeyc/util-windows

8b0a9e73a9e53e8f5f5d79ea120d06afbadaa25c — Chris Howey 9 months ago e3bc266 v0.3.0
head command
2 files changed, 76 insertions(+), 12 deletions(-)

D cmd/cal/go.sum
A cmd/head/main.go
D cmd/cal/go.sum => cmd/cal/go.sum +0 -12
@@ 1,12 0,0 @@
github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs=
github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s=
golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.9.0 h1:GRRCnKYhdQrD8kfRAdQ6Zcw1P0OcELxGLKJvtjVMZ28=
golang.org/x/term v0.9.0/go.mod h1:M6DEAAIenWoTxdKrOltXcmDY3rSplQUkrvaDU5FcQyo=

A cmd/head/main.go => cmd/head/main.go +76 -0
@@ 0,0 1,76 @@
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 first `NUM` lines;\nwhen negative, print all but the last `NUM` lines")
	flag.Parse()

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

	pos := linecount > 0
	if !pos {
		linecount = -1 * linecount
	}

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

			if pos && iIdx == linecount {
				break
			}
			if iIdx == linecount {
				iIdx = 0
			}

			if !pos && rIdx == iIdx {
				fmt.Println(lineBuffer[rIdx])
				rIdx++
			}
			if rIdx == linecount {
				rIdx = 0
			}
		}

		if pos {
			for rIdx < iIdx {
				fmt.Println(lineBuffer[rIdx])
				rIdx++
			}
		}
	}

	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)
			}
			doHead(ifile)
			ifile.Close()
		}
	} else {
		doHead(os.Stdin)
	}
}