Skip to content

Commit

Permalink
improved stdin handling (#156)
Browse files Browse the repository at this point in the history
  • Loading branch information
mike-ward authored Jun 3, 2024
1 parent 4147d5c commit 7c68314
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 14 deletions.
45 changes: 42 additions & 3 deletions src/tail/cmd_line.v → src/tail/parse_args.v
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import common
import flag
import os
import time

struct Args {
bytes i64
Expand All @@ -15,7 +17,7 @@ struct Args {
files []string
}

fn get_args(args []string) Args {
fn parse_args(args []string) Args {
mut fp := flag.new_flag_parser(args)

fp.application(app_name)
Expand Down Expand Up @@ -65,9 +67,10 @@ fn get_args(args []string) Args {
descriptors are not supported'.trim_indent())

fp.footer(common.coreutils_footer())
file_args := fp.finalize() or { exit_error(err.msg()) }
files_arg := fp.finalize() or { exit_error(err.msg()) }
from_start := bytes_arg.starts_with('+') || lines_arg.starts_with('+')
delimiter := if zero_terminated_arg { `\0` } else { `\n` }
files := scan_files_arg(files_arg)

return Args{
bytes: string_to_i64(bytes_arg) or { exit_error(err.msg()) }
Expand All @@ -80,10 +83,46 @@ fn get_args(args []string) Args {
sleep_interval: sleep_interval_arg
from_start: from_start
delimiter: delimiter
files: file_args
files: files
}
}

fn scan_files_arg(files_arg []string) []string {
mut files := []string{}

for file in files_arg {
if file == '-' {
files << stdin_to_tmp()
continue
}
files << file
}

if files.len == 0 {
files << stdin_to_tmp()
}

return files
}

const tmp_pattern = '/${app_name}-tmp-'

fn stdin_to_tmp() string {
tmp := '${os.temp_dir()}/${tmp_pattern}${time.ticks()}'
os.create(tmp) or { exit_error(err.msg()) }
mut f := os.open_append(tmp) or { exit_error(err.msg()) }
defer { f.close() }

for {
s := os.get_raw_line()
if s.len == 0 {
break
}
f.write_string(s) or { exit_error(err.msg()) }
}
return tmp
}

@[noreturn]
fn exit_success(msg string) {
println(msg)
Expand Down
13 changes: 2 additions & 11 deletions src/tail/tail.v
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub mut:
}

fn main() {
args := get_args(os.args)
args := parse_args(os.args)
tail(args, fn (s string) {
print(s)
flush_stdout()
Expand All @@ -22,16 +22,7 @@ fn main() {

fn tail(args Args, out_fn fn (string)) {
mut tail_forever := false
mut files := args.files.map(FileInfo{ name: it })

// Perhaps there is a better way to handle stdin?
if args.files.len == 0 || args.files[0] == '-' {
tmp := tmp_from_stdin()
files = [FileInfo{
name: tmp
stdin: true
}]
}
mut files := args.files.map(FileInfo{ name: it, stdin: it.contains(tmp_pattern) })

for {
for i, mut file in files {
Expand Down

0 comments on commit 7c68314

Please sign in to comment.