github.com/KEINOS/go-countline@v1.1.1-0.20221217083629-60710df7606b/_example/countline/main.go (about)

     1  //nolint:forbidigo,gochecknoglobals
     2  package main
     3  
     4  import (
     5  	"fmt"
     6  	"os"
     7  
     8  	"github.com/KEINOS/go-countline/cl"
     9  	"github.com/pkg/errors"
    10  )
    11  
    12  var msgHelp = `cl - Count the number of lines in a file.
    13  Usage:
    14  	cl [file]
    15  `
    16  
    17  // osExit is a copy of os.Exit() to be able to mock it in tests.
    18  var osExit = os.Exit
    19  
    20  func main() {
    21  	const lenArgs = 2 // program name and the file path
    22  
    23  	if len(os.Args) != lenArgs {
    24  		ExitOnError(errors.New("invalid number of arguments"))
    25  	}
    26  
    27  	pathFile := os.Args[1]
    28  
    29  	osFile, err := os.Open(pathFile)
    30  	ExitOnError(err)
    31  
    32  	count, err := cl.CountLines(osFile)
    33  	ExitOnError(err)
    34  
    35  	fmt.Println(count)
    36  }
    37  
    38  func ExitOnError(err error) {
    39  	if err != nil {
    40  		fmt.Fprintln(os.Stderr, msgHelp)
    41  		fmt.Fprintln(os.Stderr, "error:", err.Error())
    42  
    43  		osExit(1)
    44  	}
    45  }