storage.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. const path = require('path')
  2. const sgit = require('simple-git/promise')
  3. const fs = require('fs-extra')
  4. const _ = require('lodash')
  5. const stream = require('stream')
  6. const Promise = require('bluebird')
  7. const pipeline = Promise.promisify(stream.pipeline)
  8. const klaw = require('klaw')
  9. const pageHelper = require('../../../helpers/page.js')
  10. const localeFolderRegex = /^([a-z]{2}(?:-[a-z]{2})?\/)?(.*)/i
  11. /* global WIKI */
  12. const getContenType = (filePath) => {
  13. const ext = _.last(filePath.split('.'))
  14. switch (ext) {
  15. case 'md':
  16. return 'markdown'
  17. case 'html':
  18. return 'html'
  19. default:
  20. return false
  21. }
  22. }
  23. const getPagePath = (filePath) => {
  24. if (process.platform === 'win32') {
  25. filePath = filePath.replace(/\\/g, '/')
  26. }
  27. let meta = {
  28. locale: 'en',
  29. path: _.initial(filePath.split('.')).join('')
  30. }
  31. const result = localeFolderRegex.exec(meta.path)
  32. if (result[1]) {
  33. meta = {
  34. locale: result[1],
  35. path: result[2]
  36. }
  37. }
  38. return meta
  39. }
  40. module.exports = {
  41. git: null,
  42. repoPath: path.join(process.cwd(), 'data/repo'),
  43. async activated() {
  44. // not used
  45. },
  46. async deactivated() {
  47. // not used
  48. },
  49. /**
  50. * INIT
  51. */
  52. async init() {
  53. WIKI.logger.info('(STORAGE/GIT) Initializing...')
  54. this.repoPath = path.resolve(WIKI.ROOTPATH, this.config.localRepoPath)
  55. await fs.ensureDir(this.repoPath)
  56. this.git = sgit(this.repoPath)
  57. // Set custom binary path
  58. if (!_.isEmpty(this.config.gitBinaryPath)) {
  59. this.git.customBinary(this.config.gitBinaryPath)
  60. }
  61. // Initialize repo (if needed)
  62. WIKI.logger.info('(STORAGE/GIT) Checking repository state...')
  63. const isRepo = await this.git.checkIsRepo()
  64. if (!isRepo) {
  65. WIKI.logger.info('(STORAGE/GIT) Initializing local repository...')
  66. await this.git.init()
  67. }
  68. // Set default author
  69. await this.git.raw(['config', '--local', 'user.email', this.config.defaultEmail])
  70. await this.git.raw(['config', '--local', 'user.name', this.config.defaultName])
  71. // Purge existing remotes
  72. WIKI.logger.info('(STORAGE/GIT) Listing existing remotes...')
  73. const remotes = await this.git.getRemotes()
  74. if (remotes.length > 0) {
  75. WIKI.logger.info('(STORAGE/GIT) Purging existing remotes...')
  76. for (let remote of remotes) {
  77. await this.git.removeRemote(remote.name)
  78. }
  79. }
  80. // Add remote
  81. WIKI.logger.info('(STORAGE/GIT) Setting SSL Verification config...')
  82. await this.git.raw(['config', '--local', '--bool', 'http.sslVerify', _.toString(this.config.verifySSL)])
  83. switch (this.config.authType) {
  84. case 'ssh':
  85. WIKI.logger.info('(STORAGE/GIT) Setting SSH Command config...')
  86. if (this.config.sshPrivateKeyMode === 'contents') {
  87. try {
  88. this.config.sshPrivateKeyPath = path.join(WIKI.ROOTPATH, 'data/secure/git-ssh.pem')
  89. await fs.outputFile(this.config.sshPrivateKeyPath, this.config.sshPrivateKeyContent, {
  90. encoding: 'utf8',
  91. mode: 0o600
  92. })
  93. } catch (err) {
  94. console.error(err)
  95. throw err
  96. }
  97. }
  98. await this.git.addConfig('core.sshCommand', `ssh -i "${this.config.sshPrivateKeyPath}" -o StrictHostKeyChecking=no`)
  99. WIKI.logger.info('(STORAGE/GIT) Adding origin remote via SSH...')
  100. await this.git.addRemote('origin', this.config.repoUrl)
  101. break
  102. default:
  103. WIKI.logger.info('(STORAGE/GIT) Adding origin remote via HTTP/S...')
  104. let originUrl = ''
  105. if (_.startsWith(this.config.repoUrl, 'http')) {
  106. originUrl = this.config.repoUrl.replace('://', `://${this.config.basicUsername}:${this.config.basicPassword}@`)
  107. } else {
  108. originUrl = `https://${this.config.basicUsername}:${this.config.basicPassword}@${this.config.repoUrl}`
  109. }
  110. await this.git.addRemote('origin', originUrl)
  111. break
  112. }
  113. // Fetch updates for remote
  114. WIKI.logger.info('(STORAGE/GIT) Fetch updates from remote...')
  115. await this.git.raw(['remote', 'update', 'origin'])
  116. // Checkout branch
  117. const branches = await this.git.branch()
  118. if (!_.includes(branches.all, this.config.branch) && !_.includes(branches.all, `remotes/origin/${this.config.branch}`)) {
  119. throw new Error('Invalid branch! Make sure it exists on the remote first.')
  120. }
  121. WIKI.logger.info(`(STORAGE/GIT) Checking out branch ${this.config.branch}...`)
  122. await this.git.checkout(this.config.branch)
  123. // Perform initial sync
  124. await this.sync()
  125. WIKI.logger.info('(STORAGE/GIT) Initialization completed.')
  126. },
  127. /**
  128. * SYNC
  129. */
  130. async sync() {
  131. const currentCommitLog = _.get(await this.git.log(['-n', '1', this.config.branch]), 'latest', {})
  132. // Pull rebase
  133. if (_.includes(['sync', 'pull'], this.mode)) {
  134. WIKI.logger.info(`(STORAGE/GIT) Performing pull rebase from origin on branch ${this.config.branch}...`)
  135. await this.git.pull('origin', this.config.branch, ['--rebase'])
  136. }
  137. // Push
  138. if (_.includes(['sync', 'push'], this.mode)) {
  139. WIKI.logger.info(`(STORAGE/GIT) Performing push to origin on branch ${this.config.branch}...`)
  140. let pushOpts = ['--signed=if-asked']
  141. if (this.mode === 'push') {
  142. pushOpts.push('--force')
  143. }
  144. await this.git.push('origin', this.config.branch, pushOpts)
  145. }
  146. // Process Changes
  147. if (_.includes(['sync', 'pull'], this.mode)) {
  148. const latestCommitLog = _.get(await this.git.log(['-n', '1', this.config.branch]), 'latest', {})
  149. const diff = await this.git.diffSummary(['-M', currentCommitLog.hash, latestCommitLog.hash])
  150. if (_.get(diff, 'files', []).length > 0) {
  151. await this.processFiles(diff.files)
  152. }
  153. }
  154. },
  155. /**
  156. * Process Files
  157. *
  158. * @param {Array<String>} files Array of files to process
  159. */
  160. async processFiles(files) {
  161. for (const item of files) {
  162. const contentType = getContenType(item.file)
  163. if (!contentType) {
  164. continue
  165. }
  166. const contentPath = getPagePath(item.file)
  167. let itemContents = ''
  168. try {
  169. itemContents = await fs.readFile(path.join(this.repoPath, item.file), 'utf8')
  170. const pageData = WIKI.models.pages.parseMetadata(itemContents, contentType)
  171. const currentPage = await WIKI.models.pages.query().findOne({
  172. path: contentPath.path,
  173. localeCode: contentPath.locale
  174. })
  175. if (currentPage) {
  176. // Already in the DB, can mark as modified
  177. WIKI.logger.info(`(STORAGE/GIT) Page marked as modified: ${item.file}`)
  178. await WIKI.models.pages.updatePage({
  179. id: currentPage.id,
  180. title: _.get(pageData, 'title', currentPage.title),
  181. description: _.get(pageData, 'description', currentPage.description) || '',
  182. isPublished: _.get(pageData, 'isPublished', currentPage.isPublished),
  183. isPrivate: false,
  184. content: pageData.content,
  185. authorId: 1,
  186. skipStorage: true
  187. })
  188. } else {
  189. // Not in the DB, can mark as new
  190. WIKI.logger.info(`(STORAGE/GIT) Page marked as new: ${item.file}`)
  191. const pageEditor = await WIKI.models.editors.getDefaultEditor(contentType)
  192. await WIKI.models.pages.createPage({
  193. path: contentPath.path,
  194. locale: contentPath.locale,
  195. title: _.get(pageData, 'title', _.last(contentPath.path.split('/'))),
  196. description: _.get(pageData, 'description', '') || '',
  197. isPublished: _.get(pageData, 'isPublished', true),
  198. isPrivate: false,
  199. content: pageData.content,
  200. authorId: 1,
  201. editor: pageEditor,
  202. skipStorage: true
  203. })
  204. }
  205. } catch (err) {
  206. if (err.code === 'ENOENT' && item.deletions > 0 && item.insertions === 0) {
  207. // File was deleted by git, can safely mark as deleted in DB
  208. WIKI.logger.info(`(STORAGE/GIT) Page marked as deleted: ${item.file}`)
  209. await WIKI.models.pages.deletePage({
  210. path: contentPath.path,
  211. locale: contentPath.locale,
  212. skipStorage: true
  213. })
  214. } else {
  215. WIKI.logger.warn(`(STORAGE/GIT) Failed to open ${item.file}`)
  216. console.error(err)
  217. WIKI.logger.warn(err)
  218. }
  219. }
  220. }
  221. },
  222. /**
  223. * CREATE
  224. *
  225. * @param {Object} page Page to create
  226. */
  227. async created(page) {
  228. WIKI.logger.info(`(STORAGE/GIT) Committing new file ${page.path}...`)
  229. let fileName = `${page.path}.${page.getFileExtension()}`
  230. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  231. fileName = `${page.localeCode}/${fileName}`
  232. }
  233. const filePath = path.join(this.repoPath, fileName)
  234. await fs.outputFile(filePath, page.injectMetadata(), 'utf8')
  235. await this.git.add(`./${fileName}`)
  236. await this.git.commit(`docs: create ${page.path}`, fileName, {
  237. '--author': `"${page.authorName} <${page.authorEmail}>"`
  238. })
  239. },
  240. /**
  241. * UPDATE
  242. *
  243. * @param {Object} page Page to update
  244. */
  245. async updated(page) {
  246. WIKI.logger.info(`(STORAGE/GIT) Committing updated file ${page.path}...`)
  247. let fileName = `${page.path}.${page.getFileExtension()}`
  248. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  249. fileName = `${page.localeCode}/${fileName}`
  250. }
  251. const filePath = path.join(this.repoPath, fileName)
  252. await fs.outputFile(filePath, page.injectMetadata(), 'utf8')
  253. await this.git.add(`./${fileName}`)
  254. await this.git.commit(`docs: update ${page.path}`, fileName, {
  255. '--author': `"${page.authorName} <${page.authorEmail}>"`
  256. })
  257. },
  258. /**
  259. * DELETE
  260. *
  261. * @param {Object} page Page to delete
  262. */
  263. async deleted(page) {
  264. WIKI.logger.info(`(STORAGE/GIT) Committing removed file ${page.path}...`)
  265. let fileName = `${page.path}.${page.getFileExtension()}`
  266. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  267. fileName = `${page.localeCode}/${fileName}`
  268. }
  269. await this.git.rm(`./${fileName}`)
  270. await this.git.commit(`docs: delete ${page.path}`, fileName, {
  271. '--author': `"${page.authorName} <${page.authorEmail}>"`
  272. })
  273. },
  274. /**
  275. * RENAME
  276. *
  277. * @param {Object} page Page to rename
  278. */
  279. async renamed(page) {
  280. WIKI.logger.info(`(STORAGE/GIT) Committing file move from ${page.sourcePath} to ${page.destinationPath}...`)
  281. let sourceFilePath = `${page.sourcePath}.${page.getFileExtension()}`
  282. let destinationFilePath = `${page.destinationPath}.${page.getFileExtension()}`
  283. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  284. sourceFilePath = `${page.localeCode}/${sourceFilePath}`
  285. destinationFilePath = `${page.localeCode}/${destinationFilePath}`
  286. }
  287. await this.git.mv(`./${sourceFilePath}`, `./${destinationFilePath}`)
  288. await this.git.commit(`docs: rename ${page.sourcePath} to ${destinationFilePath}`, destinationFilePath, {
  289. '--author': `"${page.authorName} <${page.authorEmail}>"`
  290. })
  291. },
  292. /**
  293. * ASSET UPLOAD
  294. *
  295. * @param {Object} asset Asset to upload
  296. */
  297. async assetUploaded (asset) {
  298. WIKI.logger.info(`(STORAGE/GIT) Committing new file ${asset.path}...`)
  299. const filePath = path.join(this.repoPath, asset.path)
  300. await fs.outputFile(filePath, asset, 'utf8')
  301. await this.git.add(`./${asset.path}`)
  302. await this.git.commit(`docs: upload ${asset.path}`, asset.path, {
  303. '--author': `"${asset.authorName} <${asset.authorEmail}>"`
  304. })
  305. },
  306. /**
  307. * ASSET DELETE
  308. *
  309. * @param {Object} asset Asset to upload
  310. */
  311. async assetDeleted (asset) {
  312. WIKI.logger.info(`(STORAGE/GIT) Committing removed file ${asset.path}...`)
  313. await this.git.rm(`./${asset.path}`)
  314. await this.git.commit(`docs: delete ${asset.path}`, asset.path, {
  315. '--author': `"${asset.authorName} <${asset.authorEmail}>"`
  316. })
  317. },
  318. /**
  319. * ASSET RENAME
  320. *
  321. * @param {Object} asset Asset to upload
  322. */
  323. async assetRenamed (asset) {
  324. WIKI.logger.info(`(STORAGE/GIT) Committing file move from ${asset.sourcePath} to ${asset.destinationPath}...`)
  325. await this.git.mv(`./${asset.sourcePath}`, `./${asset.destinationPath}`)
  326. await this.git.commit(`docs: rename ${asset.sourcePath} to ${asset.destinationPath}`, asset.destinationPath, {
  327. '--author': `"${asset.authorName} <${asset.authorEmail}>"`
  328. })
  329. },
  330. /**
  331. * HANDLERS
  332. */
  333. async importAll() {
  334. WIKI.logger.info(`(STORAGE/GIT) Importing all content from local Git repo to the DB...`)
  335. await pipeline(
  336. klaw(this.repoPath, {
  337. filter: (f) => {
  338. return !_.includes(f, '.git')
  339. }
  340. }),
  341. new stream.Transform({
  342. objectMode: true,
  343. transform: async (file, enc, cb) => {
  344. const relPath = file.path.substr(this.repoPath.length + 1)
  345. if (relPath && relPath.length > 3) {
  346. WIKI.logger.info(`(STORAGE/GIT) Processing ${relPath}...`)
  347. await this.processFiles([{
  348. file: relPath,
  349. deletions: 0,
  350. insertions: 0
  351. }])
  352. }
  353. cb()
  354. }
  355. })
  356. )
  357. WIKI.logger.info('(STORAGE/GIT) Import completed.')
  358. },
  359. async syncUntracked() {
  360. WIKI.logger.info(`(STORAGE/GIT) Adding all untracked content...`)
  361. await pipeline(
  362. WIKI.models.knex.column('path', 'localeCode', 'title', 'description', 'contentType', 'content', 'isPublished', 'updatedAt').select().from('pages').where({
  363. isPrivate: false
  364. }).stream(),
  365. new stream.Transform({
  366. objectMode: true,
  367. transform: async (page, enc, cb) => {
  368. let fileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
  369. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  370. fileName = `${page.localeCode}/${fileName}`
  371. }
  372. WIKI.logger.info(`(STORAGE/GIT) Adding ${fileName}...`)
  373. const filePath = path.join(this.repoPath, fileName)
  374. await fs.outputFile(filePath, pageHelper.injectPageMetadata(page), 'utf8')
  375. await this.git.add(`./${fileName}`)
  376. cb()
  377. }
  378. })
  379. )
  380. await this.git.commit(`docs: add all untracked content`)
  381. WIKI.logger.info('(STORAGE/GIT) All content is now tracked.')
  382. }
  383. }