Previously we'd just always bogusly report "empty".
---
 tests/file.test   |  2 ++
 toys/posix/file.c | 20 +++++++++++++++++---
 2 files changed, 19 insertions(+), 3 deletions(-)
From fe3639f24995cc96f5a05eacae52f0b624f3af7c Mon Sep 17 00:00:00 2001
From: Elliott Hughes <[email protected]>
Date: Thu, 3 May 2018 16:39:21 -0700
Subject: [PATCH] Implement `file -`.

Previously we'd just always bogusly report "empty".
---
 tests/file.test   |  2 ++
 toys/posix/file.c | 20 +++++++++++++++++---
 2 files changed, 19 insertions(+), 3 deletions(-)

diff --git a/tests/file.test b/tests/file.test
index 4c7f001..3ef2248 100644
--- a/tests/file.test
+++ b/tests/file.test
@@ -22,4 +22,6 @@ testing "symlink" "file symlink" "symlink: symbolic link\n" "" ""
 testing "symlink -h" "file -h symlink" "symlink: symbolic link\n" "" ""
 testing "symlink -L" "file -L symlink" "symlink: Java class file, version 49.0\n" "" ""
 
+testing "-" "cat java.class | file -" "-: Java class file, version 49.0\n" "" ""
+
 rm empty bash.script bash.script2 env.python.script ascii java.class
diff --git a/toys/posix/file.c b/toys/posix/file.c
index 2eeb058..e29e462 100644
--- a/toys/posix/file.c
+++ b/toys/posix/file.c
@@ -356,16 +356,30 @@ void file_main(void)
   for (arg = toys.optargs; *arg; arg++) {
     char *name = *arg, *what = "cannot open";
     struct stat sb;
-    int fd = !strcmp(name, "-");
+    int fd = 0;
 
     xprintf("%s: %*s", name, (int)(TT.max_name_len - strlen(name)), "");
 
+    // If we're working on stdin, copy to a temporary file and then use
+    // an fd for that file. That way the rest of the code doesn't have to
+    // worry about non-seekable/non-mmap'able input.
+    if (!strcmp(name, "-")) {
+      FILE* tmp = tmpfile();
+      ssize_t i;
+
+      if (!tmp) perror_exit("tmpfile failed");
+      fd = fileno(tmp);
+      while ((i = xread(0, toybuf, sizeof(toybuf)))) xwrite(fd, toybuf, i);
+      xlseek(fd, 0, SEEK_SET);
+      fstat(fd, &sb);
+    }
+
     if (fd || !((toys.optflags & FLAG_L) ? stat : lstat)(name, &sb)) {
       if (fd || S_ISREG(sb.st_mode)) {
         if (!sb.st_size) what = "empty";
-        else if ((fd = openro(name, O_RDONLY)) != -1) {
+        else if (fd || (fd = openro(name, O_RDONLY)) != -1) {
           do_regular_file(fd, name, &sb);
-          if (fd) close(fd);
+          close(fd);
           continue;
         }
       } else if (S_ISFIFO(sb.st_mode)) what = "fifo";
-- 
2.17.0.441.gb46fe60e1d-goog

_______________________________________________
Toybox mailing list
[email protected]
http://lists.landley.net/listinfo.cgi/toybox-landley.net

Reply via email to