[master] dff3c2b Add std.file_exists(path) to check if path exists

Federico G. Schwindt fgsch at lodoss.net
Fri Apr 14 05:42:05 CEST 2017


commit dff3c2be8c11192075bbc32e47b08cac4fe7c471
Author: Jonathan Huot <jonathan.huot at thomsonreuters.com>
Date:   Wed Mar 29 14:59:14 2017 +0200

    Add std.file_exists(path) to check if path exists

diff --git a/bin/varnishtest/tests/m00029.vtc b/bin/varnishtest/tests/m00029.vtc
new file mode 100644
index 0000000..c92b839
--- /dev/null
+++ b/bin/varnishtest/tests/m00029.vtc
@@ -0,0 +1,22 @@
+varnishtest "Test std.file_exists"
+
+server s1 {
+	rxreq
+	txresp
+} -start
+
+varnish v1 -vcl+backend {
+	import std;
+
+	sub vcl_deliver {
+		set resp.http.existsA = std.file_exists("/non/existent");
+		set resp.http.existsB = std.file_exists("${tmpdir}/v1/_.vsm");
+	}
+} -start
+
+client c1 {
+	txreq
+	rxresp
+	expect resp.http.existsA == "false"
+	expect resp.http.existsB == "true"
+} -run
diff --git a/lib/libvmod_std/vmod.vcc b/lib/libvmod_std/vmod.vcc
index 2ebfb45..3bfa0e3 100644
--- a/lib/libvmod_std/vmod.vcc
+++ b/lib/libvmod_std/vmod.vcc
@@ -107,6 +107,16 @@ Description
 Example
 	set beresp.http.served-by = std.fileread("/etc/hostname");
 
+$Function BOOL file_exists(STRING path)
+
+Description
+	Returns `true` if path or the file pointed to by path exists,
+	`false` otherwise.
+Example
+	| if (std.file_exists("/etc/return_503")) {
+	| 	return (synth(503, "Varnish is in maintenance"));
+	| }
+
 $Function VOID collect(HEADER hdr, STRING sep=", ")
 
 Description
diff --git a/lib/libvmod_std/vmod_std.c b/lib/libvmod_std/vmod_std.c
index 601de8b..717982e 100644
--- a/lib/libvmod_std/vmod_std.c
+++ b/lib/libvmod_std/vmod_std.c
@@ -28,11 +28,15 @@
 
 #include "config.h"
 
+#include <sys/stat.h>
+#include <sys/types.h>
+
 #include <netinet/in.h>
 
 #include <ctype.h>
 #include <stdlib.h>
 #include <syslog.h>
+#include <unistd.h>
 
 #include "cache/cache.h"
 
@@ -173,6 +177,15 @@ vmod_syslog(VRT_CTX, VCL_INT fac, const char *fmt, ...)
 	WS_Release(ctx->ws, 0);
 }
 
+VCL_BOOL __match_proto__(td_std_file_exists)
+vmod_file_exists(VRT_CTX, VCL_STRING file_name)
+{
+	struct stat st;
+
+	CHECK_OBJ_NOTNULL(ctx, VRT_CTX_MAGIC);
+	return (stat(file_name, &st) == 0);
+}
+
 VCL_VOID __match_proto__(td_std_collect)
 vmod_collect(VRT_CTX, VCL_HEADER hdr, VCL_STRING sep)
 {



More information about the varnish-commit mailing list