Implement overrideable function bc.build() instead of the callback build_func(),...
[build_cache.git] / BuildCache.js
index b48702f..0c7520f 100644 (file)
@@ -28,18 +28,22 @@ let fs_stat = util.promisify(fs.stat)
 
 let BuildCache = function(diag) {
   if (!this instanceof BuildCache)
-    throw Error('BuildCache is a constructor')
+    throw new Error('BuildCache is a constructor')
   this.map = new Map()
   this.diag = diag || false
 }
 
-BuildCache.prototype.get = async function(key, build_func) {
+BuildCache.prototype.build = async function(key, result) {
+  throw new Error('not implemented')
+}
+
+BuildCache.prototype.get = async function(key, once) {
   let result = this.map.get(key)
   if (result === undefined) {
     if (this.diag)
-      console.log('building', key)
+      console.log(`building ${key}`)
     result = {deps: [key], time: Date.now()}
-    result.done = build_func(result)
+    result.done = this.build(key, result)
     this.map.set(key, result)
     try {
       await result.done
@@ -53,7 +57,7 @@ BuildCache.prototype.get = async function(key, build_func) {
   }
   else if (result.done === undefined) {
     if (this.diag)
-      console.log('checking', key)
+      console.log(`checking ${key}`)
     result.done = (
       async () => {
         for (let i = 0; i < result.deps.length; ++i) {
@@ -68,10 +72,10 @@ BuildCache.prototype.get = async function(key, build_func) {
           }
           if (stats === undefined || stats.mtimeMs > result.time) {
             if (this.diag)
-              console.log('rebuilding', key, 'reason', result.deps[i])
+              console.log(`rebuilding ${key} reason ${result.deps[i]}`)
             result.deps = [key]
             result.time = Date.now()
-            await build_func(result)
+            await this.build(key, result)
             break
           }
         }
@@ -89,7 +93,10 @@ BuildCache.prototype.get = async function(key, build_func) {
   }
   else
     await result.done
-  return result.value
+  let value = result.value
+  if (once)
+    result.value = undefined
+  return value
 }
 
 module.exports = BuildCache