From 82b133be9ee8f17741230d7211dbf7f91843a26c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jakub=20Sko=C5=99epa?= <jakub@skorepa.info>
Date: Mon, 11 Apr 2016 15:10:52 +0200
Subject: [PATCH] Generate redirects from content/redirects

---
 sitegin/config.js                          |  1 +
 sitegin/parseRedirects.js                  | 34 ++++++++++++
 sitegin/pipeline.js                        |  1 +
 sitegin/readFiles.js                       | 63 +++++++++++++++-------
 sitegin/sitegin.js                         |  1 +
 sitegin/tags.js                            |  2 +-
 sitegin/tests/content/redirects/index.toml |  1 +
 sitegin/writeFiles.js                      |  2 +
 theme/static/index.html                    | 14 -----
 theme/static/index.php                     | 17 ------
 10 files changed, 85 insertions(+), 51 deletions(-)
 create mode 100644 sitegin/parseRedirects.js
 create mode 100644 sitegin/tests/content/redirects/index.toml
 delete mode 100644 theme/static/index.html
 delete mode 100644 theme/static/index.php

diff --git a/sitegin/config.js b/sitegin/config.js
index ef505e96..9b2e93c6 100644
--- a/sitegin/config.js
+++ b/sitegin/config.js
@@ -39,6 +39,7 @@ module.exports = function() {
         staticDir: options.staticdir,
         themeDir: options.themedir,
         articlesLocation: 'articles',
+        redirectsLocation: 'redirects',
         linksPerPage: 6
       }});
     }
diff --git a/sitegin/parseRedirects.js b/sitegin/parseRedirects.js
new file mode 100644
index 00000000..352e89b9
--- /dev/null
+++ b/sitegin/parseRedirects.js
@@ -0,0 +1,34 @@
+'use strict';
+var toml = require('toml');
+var path = require('path');
+
+var readRedirectWorker = function(content, obj) {
+  if(content === undefined) throw new Error('content is undefined');
+  try {
+    obj.metadata = toml.parse(content);
+  } catch(e) {
+    console.log(obj.filename+': Failed to parse metadata');
+    throw e;
+  }
+  obj.content = obj.metadata.target;
+  console.log(obj.file)
+  obj.file = obj.file.split(path.sep).join('/');
+  if(obj.file.match(/^redirects\/(.*)index\.toml/))
+    obj.file = obj.file.replace(/^redirects\/(.*)index\.toml/,'$1');
+  else
+    obj.file = obj.file.replace(/^redirects\/(.*)\.toml/,'$1');
+  console.log(obj.file)
+  return obj;
+}
+
+module.exports = function(obj) {
+  console.log('Build step: ParseRedirects');
+  return new Promise(function(resolve, reject) {
+    var redirects = [];
+    obj.redirects.forEach(function(page) {
+      redirects.push(readRedirectWorker(page.content, page));
+    })
+    obj.redirects = redirects;
+    resolve(obj);
+  });
+}
diff --git a/sitegin/pipeline.js b/sitegin/pipeline.js
index b1e249dc..1a165148 100644
--- a/sitegin/pipeline.js
+++ b/sitegin/pipeline.js
@@ -8,6 +8,7 @@ module.exports = function(jobs) {
     'config',
     'readFiles',
     'parseHugo',
+    'parseRedirects',
     'gitInfo',
     'urls',
     'sitemap',
diff --git a/sitegin/readFiles.js b/sitegin/readFiles.js
index e467e782..a2aed1b2 100644
--- a/sitegin/readFiles.js
+++ b/sitegin/readFiles.js
@@ -1,3 +1,4 @@
+'use strict';
 /*
  * This job reads files from config.articlesLocation and loads this list to `pages`
  */
@@ -7,33 +8,57 @@ var path = require('path');
 
 module.exports = function(obj) {
   console.log('Build step: ReadFiles');
-  return new Promise(function(resolve, reject) {
+  var onFile = function(root, fileStats, next, array) {
+    var filename = path.join(root,fileStats.name);
+    var file = path.relative(obj.config.sourceDir, filename);
+    fs.readFile(filename, 'utf8', function(err,data) {
+      if(err) {
+        console.log('Error reading file '+filename)
+        console.log(err);
+      } else {
+        array.push({
+          filename: filename,
+          file: file,
+          content: data
+        })
+      }
+      next()
+    })
+  };
+
+  var promise1 = new Promise(function(resolve, reject) {
     var pages = [];
     walk.walk(path.join(obj.config.sourceDir,obj.config.articlesLocation))
-    .on('file',function(root, fileStats, next) {
-      var filename = path.join(root,fileStats.name);
-      var file = path.relative(obj.config.sourceDir, filename);
-      fs.readFile(filename, 'utf8', function(err,data) {
-        if(err) {
-          console.log('Error reading file '+filename)
-          console.log(err);
-        } else {
-          pages.push({
-            filename: filename,
-            file: file,
-            content: data
-          })
-        }
-        next()
-      })
+    .on('file',function(root,fileStats,next) {
+      onFile(root,fileStats,next,pages);
+    })
+    .on('errors',function(root, nodeStatsArray, next) {
+      console.log('Walker error', root, nodeStatsArray);
+      next();
+    })
+    .on('end', function() {
+      resolve({type: 'pages', val: pages});
+    })
+  })
+
+  var promise2 = new Promise(function(resolve, reject) {
+    let redirects = [];
+    walk.walk(path.join(obj.config.sourceDir,obj.config.redirectsLocation))
+    .on('file',function(root,fileStats,next) {
+      onFile(root,fileStats,next,redirects);
     })
     .on('errors',function(root, nodeStatsArray, next) {
       console.log('Walker error', root, nodeStatsArray);
       next();
     })
     .on('end', function() {
-      obj.pages = pages;
-      resolve(obj);
+      resolve({type: 'redirects', val: redirects});
     })
   })
+  return Promise.all([promise1,promise2]).then(function(arr) {
+    arr.forEach(function(v) {
+      obj[v.type] = v.val;
+    });
+    return obj;
+  });
 }
diff --git a/sitegin/sitegin.js b/sitegin/sitegin.js
index be2db354..68387c57 100644
--- a/sitegin/sitegin.js
+++ b/sitegin/sitegin.js
@@ -17,6 +17,7 @@ module.exports = function(config) {
     ['writeFiles', './writeFiles'],
     ['resetJobs', './resetJobs'],
     ['sitemap', './sitemap'],
+    ['parseRedirects','./parseRedirects'],
 
     ['pipeline','./pipeline']
   )
diff --git a/sitegin/tags.js b/sitegin/tags.js
index be2386ed..bf8a32de 100644
--- a/sitegin/tags.js
+++ b/sitegin/tags.js
@@ -42,7 +42,7 @@ module.exports = function(obj) {
     });
 
     obj.tags = [];
-    obj.redirects = [];
+    if(!Array.isArray(obj.redirects)) obj.redirects = [];
 
     var generateTagPages = function(file, pageList) {
       var pg = {};
diff --git a/sitegin/tests/content/redirects/index.toml b/sitegin/tests/content/redirects/index.toml
new file mode 100644
index 00000000..6dc60975
--- /dev/null
+++ b/sitegin/tests/content/redirects/index.toml
@@ -0,0 +1 @@
+target = "/tag/clanek/1/"
diff --git a/sitegin/writeFiles.js b/sitegin/writeFiles.js
index afc4ff2a..002e8354 100644
--- a/sitegin/writeFiles.js
+++ b/sitegin/writeFiles.js
@@ -26,6 +26,8 @@ module.exports = function(obj) {
           var f = path.join(builddir,article.file,'index.'+o.type);
           doWrite(f, o.content);
         })
+      } else {
+        console.log(article);
       }
     }
     obj.pages.forEach(function(o) { writeFile(o); })
diff --git a/theme/static/index.html b/theme/static/index.html
deleted file mode 100644
index 3989517e..00000000
--- a/theme/static/index.html
+++ /dev/null
@@ -1,14 +0,0 @@
-<!DOCTYPE HTML>
-<html lang="en-US">
-    <head>
-        <meta charset="UTF-8">
-        <meta http-equiv="refresh" content="1;url=/tag/clanek">
-        <script type="text/javascript">
-            window.location.href = "/tag/clanek"
-        </script>
-        <title>Přesměrování...</title>
-    </head>
-    <body>
-        Pokud nebudete přesměrováni automaticky tak následujte <a href='/tag/clanek'>tento odkaz</a>
-    </body>
-</html>
diff --git a/theme/static/index.php b/theme/static/index.php
deleted file mode 100644
index bf2dbaef..00000000
--- a/theme/static/index.php
+++ /dev/null
@@ -1,17 +0,0 @@
-<?php
-header("location: /tag/clanek");
-?>
-<!DOCTYPE HTML>
-<html lang="en-US">
-    <head>
-        <meta charset="UTF-8">
-        <meta http-equiv="refresh" content="1;url=/tag/clanek">
-        <script type="text/javascript">
-            window.location.href = "/tag/clanek"
-        </script>
-        <title>Přesměrování...</title>
-    </head>
-    <body>
-        Pokud nebudete přesměrováni automaticky tak následujte <a href='/tag/clanek'>tento odkaz</a>
-    </body>
-</html>
-- 
GitLab