add head function

This commit is contained in:
Lisa Milne 2023-12-14 15:20:33 +10:00
parent c618fb3ac1
commit 8a6e6bb619

View file

@ -1293,6 +1293,90 @@ Options:
return main(args);
});
clite.commands.load('head',function(args,env,io) {
var stdio = io.include('stdio');
var clite = io.include('clite');
var lines = 10;
function help() {
stdio.printf(`
head - copy the first part of files
Usage: head [OPTION] <FILE>
Options:
-n the number of lines to print (default 10)
-? Print this help information
`);
}
function writeFile(fd) {
if (!fd) {
stdio.fprintf(io.stderr,'could not open file\n');
io.exit(1);
return;
}
var l;
for (var i=0; i<lines && (l = stdio.readLine(fd)) != null; i++) {
stdio.printf('%s\n',l);
}
stdio.close(fd);
io.exit(0);
}
function main(args) {
var lnext = false;
var short = null;
var file = null;
for (var i=1; i<args.length; i++) {
if (args[i][0] == '-') {
for (var j=1; j<args[i].length; j++) {
switch (args[i][j]) {
case '?':
help();
return 0;
break;
case 'n':
lnext = true;
break;
default:
stdio.fprintf(io.stderr,'unknown argument: -%c\n',args[i][j]);
}
}
}else if (lnext) {
lines = parseInt(args[i]);
if (lines < 1) {
stdio.fprintf(io.stderr,'invalid lines count "%d"\n',lines);
return 1;
}
lnext = false;
}else if (file == null) {
short = args[i];
file = clite.resolvePath(args[i]);
}else{
stdio.fprintf(io.stderr,'unknown argument: %s\n',args[i]);
}
}
if (file == null) {
stdio.write(io.stderr,'no file specified\n');
return 1;
}
var fd = stdio.open(file,stdio.flags.O_RDONLY,writeFile);
if (!fd) {
stdio.fprintf(io.stderr,'could not open file: %s\n',short);
return 1;
}
return null;
}
return main(args);
});
if (window.location.protocol == 'file:')
clite.commands.load('test',function(args,env,io) {
var stdio = io.include('stdio');