From 435ded0c60906c6db23e6567da3ca2c13ce42eb6 Mon Sep 17 00:00:00 2001
From: Nils Schneider <nils@nilsschneider.net>
Date: Mon, 31 Aug 2015 19:56:21 +0200
Subject: [PATCH] gluon-announce: build a tree of functions first

collect_dir() will now pre-load all files and return a function that will
collect all information.
---
 .../files/usr/lib/lua/gluon/announce.lua      | 26 ++++++++++++++-----
 .../files/usr/lib/lua/gluon/announced.lua     |  7 ++++-
 2 files changed, 25 insertions(+), 8 deletions(-)

diff --git a/package/gluon-announce/files/usr/lib/lua/gluon/announce.lua b/package/gluon-announce/files/usr/lib/lua/gluon/announce.lua
index 444dbd338..8a91e6f8a 100644
--- a/package/gluon-announce/files/usr/lib/lua/gluon/announce.lua
+++ b/package/gluon-announce/files/usr/lib/lua/gluon/announce.lua
@@ -10,24 +10,36 @@ local function collect_entry(entry)
 	if fs.stat(entry, 'type') == 'dir' then
 		return collect_dir(entry)
 	else
-		return setfenv(loadfile(entry), _M)()
+		return loadfile(entry)
 	end
 end
 
 function collect_dir(dir)
-	local ret = { [{}] = true }
+	local fns = {}
 
 	for entry in fs.dir(dir) do
 		if entry:sub(1, 1) ~= '.' then
-			local ok, val = pcall(collect_entry, dir .. '/' .. entry)
+			local fn, err = collect_entry(dir .. '/' .. entry)
+			if fn then
+				fns[entry] = fn
+			else
+				io.stderr:write(err, '\n')
+			end
+		end
+	end
+
+	return function ()
+		local ret = { [{}] = true }
+
+		for k, v in pairs(fns) do
+			local ok, val = pcall(setfenv(v, _M))
 			if ok then
-				ret[entry] = val
+				ret[k] = val
 			else
 				io.stderr:write(val, '\n')
 			end
 		end
-	end
 
-	return ret
+		return ret
+	end
 end
-
diff --git a/package/gluon-announced/files/usr/lib/lua/gluon/announced.lua b/package/gluon-announced/files/usr/lib/lua/gluon/announced.lua
index a9de80e63..af2291fe0 100644
--- a/package/gluon-announced/files/usr/lib/lua/gluon/announced.lua
+++ b/package/gluon-announced/files/usr/lib/lua/gluon/announced.lua
@@ -2,9 +2,14 @@ local announce = require 'gluon.announce'
 local deflate = require 'deflate'
 local json = require 'luci.jsonc'
 
+local memoize = {}
 
 local function collect(type)
-  return announce.collect_dir('/lib/gluon/announce/' .. type .. '.d')
+  if not memoize[type] then
+    memoize[type] = announce.collect_dir('/lib/gluon/announce/' .. type .. '.d')
+  end
+
+  return memoize[type]()
 end
 
 
-- 
GitLab