Created
September 2, 2013 06:44
-
-
Save stevedonovan/6409847 to your computer and use it in GitHub Desktop.
A simple implementation of `head` in Nimrod
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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