git-sync.js 1.95 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
'use strict'

/* global wiki */

const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs-extra'))
const klaw = require('klaw')
const moment = require('moment')
const path = require('path')
const entryHelper = require('../helpers/entry')

12
module.exports = (job) => {
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
  return wiki.git.resync().then(() => {
    // -> Stream all documents

    let cacheJobs = []
    let jobCbStreamDocsResolve = null
    let jobCbStreamDocs = new Promise((resolve, reject) => {
      jobCbStreamDocsResolve = resolve
    })

    klaw(wiki.REPOPATH).on('data', function (item) {
      if (path.extname(item.path) === '.md' && path.basename(item.path) !== 'README.md') {
        let entryPath = entryHelper.parsePath(entryHelper.getEntryPathFromFullPath(item.path))
        let cachePath = entryHelper.getCachePath(entryPath)

        // -> Purge outdated cache

        cacheJobs.push(
          fs.statAsync(cachePath).then((st) => {
            return moment(st.mtime).isBefore(item.stats.mtime) ? 'expired' : 'active'
          }).catch((err) => {
            return (err.code !== 'EEXIST') ? err : 'new'
          }).then((fileStatus) => {
            // -> Delete expired cache file

            if (fileStatus === 'expired') {
              return fs.unlinkAsync(cachePath).return(fileStatus)
            }

            return fileStatus
          }).then((fileStatus) => {
            // -> Update cache and search index

            if (fileStatus !== 'active') {
              return global.entries.updateCache(entryPath).then(entry => {
                process.send({
                  action: 'searchAdd',
                  content: entry
                })
                return true
              })
            }

            return true
          })
        )
      }
    }).on('end', () => {
      jobCbStreamDocsResolve(Promise.all(cacheJobs))
    })

    return jobCbStreamDocs
NGPixel's avatar
NGPixel committed
64 65 66
  }).then(() => {
    wiki.logger.info('Git remote repository sync: DONE')
    return true
67 68
  })
}