Skip to content

Instantly share code, notes, and snippets.

@stevedonovan
Created September 2, 2013 06:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevedonovan/6409847 to your computer and use it in GitHub Desktop.
Save stevedonovan/6409847 to your computer and use it in GitHub Desktop.
A simple implementation of `head` in Nimrod
import parseopt
from strutils import parseInt
from os import existsFile
const usage = """
head [flags] filename
-n: number of lines (default 10)
-h,--help: this help
-v,--version: version
"""
proc showUsage(msg: string) =
if msg != nil: echo("head: ",msg)
quit(usage,1)
proc head(file: string, n: int) =
if not existsFile(file): quit("file " & file & " does not exist")
var
f = open(file)
i = 0
for line in f.lines:
echo(line)
i += 1
if i == n: break
proc parseCommands() =
var
files: seq[string]
n = 10
newSeq(files,0)
for kind, key, val in getopt():
case kind
of cmdArgument:
files.add(key)
of cmdLongOption, cmdShortOption:
case key
of "help", "h": showUsage(nil)
of "n":
n = parseInt(val)
of "version", "v":
echo("1.0")
return
of cmdEnd: assert(false) # cannot happen
if len(files) == 0:
# no filename has been given, so we show the help:
showUsage("please supply filename")
if len(files) == 1:
head(files[0],n)
else:
for f in files:
echo("----- ",f)
head(f,n)
parseCommands()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment