build: Enable detailed version information when built from shallow clone or tarball

Change-Id: Ia2ec086dff822989ba54117678a41394e990f996
Refs: #1915
diff --git a/.gitignore b/.gitignore
index fc3231c..10263e6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -11,4 +11,7 @@
 build/
 
 # Compiled python code
-**/*.pyc
+*.pyc
+
+# Other
+VERSION
diff --git a/wscript b/wscript
index 7a3e7fc..3d806d2 100644
--- a/wscript
+++ b/wscript
@@ -7,6 +7,7 @@
 APPNAME = "ndn-cxx"
 PACKAGE_BUGREPORT = "http://redmine.named-data.net/projects/ndn-cxx"
 PACKAGE_URL = "http://named-data.net/doc/ndn-cxx/"
+GIT_TAG_PREFIX = "ndn-cxx-"
 
 def options(opt):
     opt.load(['compiler_cxx', 'gnu_dirs', 'c_osx'])
@@ -248,16 +249,49 @@
     Context.g_module.VERSION_BASE = Context.g_module.VERSION
     Context.g_module.VERSION_SPLIT = [v for v in VERSION_BASE.split('.')]
 
+    didGetVersion = False
     try:
-        cmd = ['git', 'describe', '--match', 'ndn-cxx-*']
+        cmd = ['git', 'describe', '--always', '--match', '%s*' % GIT_TAG_PREFIX]
         p = Utils.subprocess.Popen(cmd, stdout=Utils.subprocess.PIPE,
                                    stderr=None, stdin=None)
-        out = p.communicate()[0].strip()
-        if p.returncode == 0 and out != "":
-            Context.g_module.VERSION = out[8:]
-    except:
+        out = str(p.communicate()[0].strip())
+        didGetVersion = (p.returncode == 0 and out != "")
+        if didGetVersion:
+            if out.startswith(GIT_TAG_PREFIX):
+                Context.g_module.VERSION = out[len(GIT_TAG_PREFIX):]
+            else:
+                Context.g_module.VERSION = "%s-commit-%s" % (Context.g_module.VERSION_BASE, out)
+    except OSError:
         pass
 
+    versionFile = ctx.path.find_node('VERSION')
+
+    if not didGetVersion and versionFile is not None:
+        try:
+            Context.g_module.VERSION = versionFile.read()
+            return
+        except (OSError, IOError):
+            pass
+
+    # version was obtained from git, update VERSION file if necessary
+    if versionFile is not None:
+        try:
+            version = versionFile.read()
+            if version == Context.g_module.VERSION:
+                return # no need to update
+        except (OSError, IOError):
+            Logs.warn("VERSION file exists, but not readable")
+    else:
+        versionFile = ctx.path.make_node('VERSION')
+
+    if versionFile is None:
+        return
+
+    try:
+        versionFile.write(Context.g_module.VERSION)
+    except (OSError, IOError):
+        Logs.warn("VERSION file is not writeable")
+
 def dist(ctx):
     version(ctx)