storage.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 os = require('os')
  10. const pageHelper = require('../../../helpers/page')
  11. const assetHelper = require('../../../helpers/asset')
  12. const commonDisk = require('../disk/common')
  13. /* global WIKI */
  14. module.exports = {
  15. git: null,
  16. repoPath: path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, 'repo'),
  17. async activated() {
  18. // not used
  19. },
  20. async deactivated() {
  21. // not used
  22. },
  23. /**
  24. * INIT
  25. */
  26. async init() {
  27. WIKI.logger.info('(STORAGE/GIT) Initializing...')
  28. this.repoPath = path.resolve(WIKI.ROOTPATH, this.config.localRepoPath)
  29. await fs.ensureDir(this.repoPath)
  30. this.git = sgit(this.repoPath)
  31. // Set custom binary path
  32. if (!_.isEmpty(this.config.gitBinaryPath)) {
  33. this.git.customBinary(this.config.gitBinaryPath)
  34. }
  35. // Initialize repo (if needed)
  36. WIKI.logger.info('(STORAGE/GIT) Checking repository state...')
  37. const isRepo = await this.git.checkIsRepo()
  38. if (!isRepo) {
  39. WIKI.logger.info('(STORAGE/GIT) Initializing local repository...')
  40. await this.git.init()
  41. }
  42. // Set default author
  43. await this.git.raw(['config', '--local', 'user.email', this.config.defaultEmail])
  44. await this.git.raw(['config', '--local', 'user.name', this.config.defaultName])
  45. // Purge existing remotes
  46. WIKI.logger.info('(STORAGE/GIT) Listing existing remotes...')
  47. const remotes = await this.git.getRemotes()
  48. if (remotes.length > 0) {
  49. WIKI.logger.info('(STORAGE/GIT) Purging existing remotes...')
  50. for (let remote of remotes) {
  51. await this.git.removeRemote(remote.name)
  52. }
  53. }
  54. // Add remote
  55. WIKI.logger.info('(STORAGE/GIT) Setting SSL Verification config...')
  56. await this.git.raw(['config', '--local', '--bool', 'http.sslVerify', _.toString(this.config.verifySSL)])
  57. switch (this.config.authType) {
  58. case 'ssh':
  59. WIKI.logger.info('(STORAGE/GIT) Setting SSH Command config...')
  60. if (this.config.sshPrivateKeyMode === 'contents') {
  61. try {
  62. this.config.sshPrivateKeyPath = path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, 'secure/git-ssh.pem')
  63. await fs.outputFile(this.config.sshPrivateKeyPath, this.config.sshPrivateKeyContent + os.EOL, {
  64. encoding: 'utf8',
  65. mode: 0o600
  66. })
  67. } catch (err) {
  68. WIKI.logger.error(err)
  69. throw err
  70. }
  71. }
  72. await this.git.addConfig('core.sshCommand', `ssh -i "${this.config.sshPrivateKeyPath}" -o StrictHostKeyChecking=no`)
  73. WIKI.logger.info('(STORAGE/GIT) Adding origin remote via SSH...')
  74. await this.git.addRemote('origin', this.config.repoUrl)
  75. break
  76. default:
  77. WIKI.logger.info('(STORAGE/GIT) Adding origin remote via HTTP/S...')
  78. let originUrl = ''
  79. if (_.startsWith(this.config.repoUrl, 'http')) {
  80. originUrl = this.config.repoUrl.replace('://', `://${encodeURI(this.config.basicUsername)}:${encodeURI(this.config.basicPassword)}@`)
  81. } else {
  82. originUrl = `https://${encodeURI(this.config.basicUsername)}:${encodeURI(this.config.basicPassword)}@${this.config.repoUrl}`
  83. }
  84. await this.git.addRemote('origin', originUrl)
  85. break
  86. }
  87. // Fetch updates for remote
  88. WIKI.logger.info('(STORAGE/GIT) Fetch updates from remote...')
  89. await this.git.raw(['remote', 'update', 'origin'])
  90. // Checkout branch
  91. const branches = await this.git.branch()
  92. if (!_.includes(branches.all, this.config.branch) && !_.includes(branches.all, `remotes/origin/${this.config.branch}`)) {
  93. throw new Error('Invalid branch! Make sure it exists on the remote first.')
  94. }
  95. WIKI.logger.info(`(STORAGE/GIT) Checking out branch ${this.config.branch}...`)
  96. await this.git.checkout(this.config.branch)
  97. // Perform initial sync
  98. await this.sync()
  99. WIKI.logger.info('(STORAGE/GIT) Initialization completed.')
  100. },
  101. /**
  102. * SYNC
  103. */
  104. async sync() {
  105. const currentCommitLog = _.get(await this.git.log(['-n', '1', this.config.branch]), 'latest', {})
  106. const rootUser = await WIKI.models.users.getRootUser()
  107. // Pull rebase
  108. if (_.includes(['sync', 'pull'], this.mode)) {
  109. WIKI.logger.info(`(STORAGE/GIT) Performing pull rebase from origin on branch ${this.config.branch}...`)
  110. await this.git.pull('origin', this.config.branch, ['--rebase'])
  111. }
  112. // Push
  113. if (_.includes(['sync', 'push'], this.mode)) {
  114. WIKI.logger.info(`(STORAGE/GIT) Performing push to origin on branch ${this.config.branch}...`)
  115. let pushOpts = ['--signed=if-asked']
  116. if (this.mode === 'push') {
  117. pushOpts.push('--force')
  118. }
  119. await this.git.push('origin', this.config.branch, pushOpts)
  120. }
  121. // Process Changes
  122. if (_.includes(['sync', 'pull'], this.mode)) {
  123. const latestCommitLog = _.get(await this.git.log(['-n', '1', this.config.branch]), 'latest', {})
  124. const diff = await this.git.diffSummary(['-M', currentCommitLog.hash, latestCommitLog.hash])
  125. if (_.get(diff, 'files', []).length > 0) {
  126. let filesToProcess = []
  127. for (const f of diff.files) {
  128. const fMoved = f.file.split(' => ')
  129. const fName = fMoved.length === 2 ? fMoved[1] : fMoved[0]
  130. const fPath = path.join(this.repoPath, fName)
  131. let fStats = { size: 0 }
  132. try {
  133. fStats = await fs.stat(fPath)
  134. } catch (err) {
  135. if (err.code !== 'ENOENT') {
  136. WIKI.logger.warn(`(STORAGE/GIT) Failed to access file ${f.file}! Skipping...`)
  137. continue
  138. }
  139. }
  140. filesToProcess.push({
  141. ...f,
  142. file: {
  143. path: fPath,
  144. stats: fStats
  145. },
  146. oldPath: fMoved[0],
  147. relPath: fName
  148. })
  149. }
  150. await this.processFiles(filesToProcess, rootUser)
  151. }
  152. }
  153. },
  154. /**
  155. * Process Files
  156. *
  157. * @param {Array<String>} files Array of files to process
  158. */
  159. async processFiles(files, user) {
  160. for (const item of files) {
  161. const contentType = pageHelper.getContentType(item.relPath)
  162. const fileExists = await fs.pathExists(item.file.path)
  163. if (!item.binary && contentType) {
  164. // -> Page
  165. if (fileExists && !item.importAll && item.relPath !== item.oldPath) {
  166. // Page was renamed by git, so rename in DB
  167. WIKI.logger.info(`(STORAGE/GIT) Page marked as renamed: from ${item.oldPath} to ${item.relPath}`)
  168. const contentPath = pageHelper.getPagePath(item.oldPath)
  169. const contentDestinationPath = pageHelper.getPagePath(item.relPath)
  170. await WIKI.models.pages.movePage({
  171. user: user,
  172. path: contentPath.path,
  173. destinationPath: contentDestinationPath.path,
  174. locale: contentPath.locale,
  175. destinationLocale: contentPath.locale,
  176. skipStorage: true
  177. })
  178. } else if (!fileExists && !item.importAll && item.deletions > 0 && item.insertions === 0) {
  179. // Page was deleted by git, can safely mark as deleted in DB
  180. WIKI.logger.info(`(STORAGE/GIT) Page marked as deleted: ${item.relPath}`)
  181. const contentPath = pageHelper.getPagePath(item.relPath)
  182. await WIKI.models.pages.deletePage({
  183. user: user,
  184. path: contentPath.path,
  185. locale: contentPath.locale,
  186. skipStorage: true
  187. })
  188. continue
  189. }
  190. try {
  191. await commonDisk.processPage({
  192. user,
  193. relPath: item.relPath,
  194. fullPath: this.repoPath,
  195. contentType: contentType,
  196. moduleName: 'GIT'
  197. })
  198. } catch (err) {
  199. WIKI.logger.warn(`(STORAGE/GIT) Failed to process ${item.relPath}`)
  200. WIKI.logger.warn(err)
  201. }
  202. } else {
  203. // -> Asset
  204. if (fileExists && !item.importAll && ((item.before === item.after) || (item.deletions === 0 && item.insertions === 0))) {
  205. // Asset was renamed by git, so rename in DB
  206. WIKI.logger.info(`(STORAGE/GIT) Asset marked as renamed: from ${item.oldPath} to ${item.relPath}`)
  207. const fileHash = assetHelper.generateHash(item.relPath)
  208. const assetToRename = await WIKI.models.assets.query().findOne({ hash: fileHash })
  209. if (assetToRename) {
  210. await WIKI.models.assets.query().patch({
  211. filename: item.relPath,
  212. hash: fileHash
  213. }).findById(assetToRename.id)
  214. await assetToRename.deleteAssetCache()
  215. } else {
  216. WIKI.logger.info(`(STORAGE/GIT) Asset was not found in the DB, nothing to rename: ${item.relPath}`)
  217. }
  218. continue
  219. } else if (!fileExists && !item.importAll && ((item.before > 0 && item.after === 0) || (item.deletions > 0 && item.insertions === 0))) {
  220. // Asset was deleted by git, can safely mark as deleted in DB
  221. WIKI.logger.info(`(STORAGE/GIT) Asset marked as deleted: ${item.relPath}`)
  222. const fileHash = assetHelper.generateHash(item.relPath)
  223. const assetToDelete = await WIKI.models.assets.query().findOne({ hash: fileHash })
  224. if (assetToDelete) {
  225. await WIKI.models.knex('assetData').where('id', assetToDelete.id).del()
  226. await WIKI.models.assets.query().deleteById(assetToDelete.id)
  227. await assetToDelete.deleteAssetCache()
  228. } else {
  229. WIKI.logger.info(`(STORAGE/GIT) Asset was not found in the DB, nothing to delete: ${item.relPath}`)
  230. }
  231. continue
  232. }
  233. try {
  234. await commonDisk.processAsset({
  235. user,
  236. relPath: item.relPath,
  237. file: item.file,
  238. contentType: contentType,
  239. moduleName: 'GIT'
  240. })
  241. } catch (err) {
  242. WIKI.logger.warn(`(STORAGE/GIT) Failed to process asset ${item.relPath}`)
  243. WIKI.logger.warn(err)
  244. }
  245. }
  246. }
  247. },
  248. /**
  249. * CREATE
  250. *
  251. * @param {Object} page Page to create
  252. */
  253. async created(page) {
  254. WIKI.logger.info(`(STORAGE/GIT) Committing new file [${page.localeCode}] ${page.path}...`)
  255. let fileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
  256. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  257. fileName = `${page.localeCode}/${fileName}`
  258. }
  259. const filePath = path.join(this.repoPath, fileName)
  260. await fs.outputFile(filePath, page.injectMetadata(), 'utf8')
  261. await this.git.add(`./${fileName}`)
  262. await this.git.commit(`docs: create ${page.path}`, fileName, {
  263. '--author': `"${page.authorName} <${page.authorEmail}>"`
  264. })
  265. },
  266. /**
  267. * UPDATE
  268. *
  269. * @param {Object} page Page to update
  270. */
  271. async updated(page) {
  272. WIKI.logger.info(`(STORAGE/GIT) Committing updated file [${page.localeCode}] ${page.path}...`)
  273. let fileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
  274. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  275. fileName = `${page.localeCode}/${fileName}`
  276. }
  277. const filePath = path.join(this.repoPath, fileName)
  278. await fs.outputFile(filePath, page.injectMetadata(), 'utf8')
  279. await this.git.add(`./${fileName}`)
  280. await this.git.commit(`docs: update ${page.path}`, fileName, {
  281. '--author': `"${page.authorName} <${page.authorEmail}>"`
  282. })
  283. },
  284. /**
  285. * DELETE
  286. *
  287. * @param {Object} page Page to delete
  288. */
  289. async deleted(page) {
  290. WIKI.logger.info(`(STORAGE/GIT) Committing removed file [${page.localeCode}] ${page.path}...`)
  291. let fileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
  292. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  293. fileName = `${page.localeCode}/${fileName}`
  294. }
  295. await this.git.rm(`./${fileName}`)
  296. await this.git.commit(`docs: delete ${page.path}`, fileName, {
  297. '--author': `"${page.authorName} <${page.authorEmail}>"`
  298. })
  299. },
  300. /**
  301. * RENAME
  302. *
  303. * @param {Object} page Page to rename
  304. */
  305. async renamed(page) {
  306. WIKI.logger.info(`(STORAGE/GIT) Committing file move from [${page.localeCode}] ${page.path} to [${page.destinationLocaleCode}] ${page.destinationPath}...`)
  307. let sourceFileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
  308. let destinationFileName = `${page.destinationPath}.${pageHelper.getFileExtension(page.contentType)}`
  309. if (WIKI.config.lang.namespacing) {
  310. if (WIKI.config.lang.code !== page.localeCode) {
  311. sourceFileName = `${page.localeCode}/${sourceFileName}`
  312. }
  313. if (WIKI.config.lang.code !== page.destinationLocaleCode) {
  314. destinationFileName = `${page.destinationLocaleCode}/${destinationFileName}`
  315. }
  316. }
  317. const sourceFilePath = path.join(this.repoPath, sourceFileName)
  318. const destinationFilePath = path.join(this.repoPath, destinationFileName)
  319. await fs.move(sourceFilePath, destinationFilePath)
  320. await this.git.rm(`./${sourceFileName}`)
  321. await this.git.add(`./${destinationFileName}`)
  322. await this.git.commit(`docs: rename ${page.path} to ${page.destinationPath}`, [sourceFilePath, destinationFilePath], {
  323. '--author': `"${page.moveAuthorName} <${page.moveAuthorEmail}>"`
  324. })
  325. },
  326. /**
  327. * ASSET UPLOAD
  328. *
  329. * @param {Object} asset Asset to upload
  330. */
  331. async assetUploaded (asset) {
  332. WIKI.logger.info(`(STORAGE/GIT) Committing new file ${asset.path}...`)
  333. const filePath = path.join(this.repoPath, asset.path)
  334. await fs.outputFile(filePath, asset.data, 'utf8')
  335. await this.git.add(`./${asset.path}`)
  336. await this.git.commit(`docs: upload ${asset.path}`, asset.path, {
  337. '--author': `"${asset.authorName} <${asset.authorEmail}>"`
  338. })
  339. },
  340. /**
  341. * ASSET DELETE
  342. *
  343. * @param {Object} asset Asset to upload
  344. */
  345. async assetDeleted (asset) {
  346. WIKI.logger.info(`(STORAGE/GIT) Committing removed file ${asset.path}...`)
  347. await this.git.rm(`./${asset.path}`)
  348. await this.git.commit(`docs: delete ${asset.path}`, asset.path, {
  349. '--author': `"${asset.authorName} <${asset.authorEmail}>"`
  350. })
  351. },
  352. /**
  353. * ASSET RENAME
  354. *
  355. * @param {Object} asset Asset to upload
  356. */
  357. async assetRenamed (asset) {
  358. WIKI.logger.info(`(STORAGE/GIT) Committing file move from ${asset.path} to ${asset.destinationPath}...`)
  359. await this.git.mv(`./${asset.path}`, `./${asset.destinationPath}`)
  360. await this.git.commit(`docs: rename ${asset.path} to ${asset.destinationPath}`, [asset.path, asset.destinationPath], {
  361. '--author': `"${asset.moveAuthorName} <${asset.moveAuthorEmail}>"`
  362. })
  363. },
  364. async getLocalLocation (asset) {
  365. return path.join(this.repoPath, asset.path)
  366. },
  367. /**
  368. * HANDLERS
  369. */
  370. async importAll() {
  371. WIKI.logger.info(`(STORAGE/GIT) Importing all content from local Git repo to the DB...`)
  372. const rootUser = await WIKI.models.users.getRootUser()
  373. await pipeline(
  374. klaw(this.repoPath, {
  375. filter: (f) => {
  376. return !_.includes(f, '.git')
  377. }
  378. }),
  379. new stream.Transform({
  380. objectMode: true,
  381. transform: async (file, enc, cb) => {
  382. const relPath = file.path.substr(this.repoPath.length + 1)
  383. if (file.stats.size < 1) {
  384. // Skip directories and zero-byte files
  385. return cb()
  386. } else if (relPath && relPath.length > 3) {
  387. WIKI.logger.info(`(STORAGE/GIT) Processing ${relPath}...`)
  388. await this.processFiles([{
  389. user: rootUser,
  390. relPath,
  391. file,
  392. deletions: 0,
  393. insertions: 0,
  394. importAll: true
  395. }], rootUser)
  396. }
  397. cb()
  398. }
  399. })
  400. )
  401. commonDisk.clearFolderCache()
  402. WIKI.logger.info('(STORAGE/GIT) Import completed.')
  403. },
  404. async syncUntracked() {
  405. WIKI.logger.info(`(STORAGE/GIT) Adding all untracked content...`)
  406. // -> Pages
  407. await pipeline(
  408. WIKI.models.knex.column('id', 'path', 'localeCode', 'title', 'description', 'contentType', 'content', 'isPublished', 'updatedAt', 'createdAt', 'editorKey').select().from('pages').where({
  409. isPrivate: false
  410. }).stream(),
  411. new stream.Transform({
  412. objectMode: true,
  413. transform: async (page, enc, cb) => {
  414. const pageObject = await WIKI.models.pages.query().findById(page.id)
  415. page.tags = await pageObject.$relatedQuery('tags')
  416. let fileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
  417. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  418. fileName = `${page.localeCode}/${fileName}`
  419. }
  420. WIKI.logger.info(`(STORAGE/GIT) Adding page ${fileName}...`)
  421. const filePath = path.join(this.repoPath, fileName)
  422. await fs.outputFile(filePath, pageHelper.injectPageMetadata(page), 'utf8')
  423. await this.git.add(`./${fileName}`)
  424. cb()
  425. }
  426. })
  427. )
  428. // -> Assets
  429. const assetFolders = await WIKI.models.assetFolders.getAllPaths()
  430. await pipeline(
  431. WIKI.models.knex.column('filename', 'folderId', 'data').select().from('assets').join('assetData', 'assets.id', '=', 'assetData.id').stream(),
  432. new stream.Transform({
  433. objectMode: true,
  434. transform: async (asset, enc, cb) => {
  435. const filename = (asset.folderId && asset.folderId > 0) ? `${_.get(assetFolders, asset.folderId)}/${asset.filename}` : asset.filename
  436. WIKI.logger.info(`(STORAGE/GIT) Adding asset ${filename}...`)
  437. await fs.outputFile(path.join(this.repoPath, filename), asset.data)
  438. await this.git.add(`./${filename}`)
  439. cb()
  440. }
  441. })
  442. )
  443. await this.git.commit(`docs: add all untracked content`)
  444. WIKI.logger.info('(STORAGE/GIT) All content is now tracked.')
  445. },
  446. async purge() {
  447. WIKI.logger.info(`(STORAGE/GIT) Purging local repository...`)
  448. await fs.emptyDir(this.repoPath)
  449. WIKI.logger.info('(STORAGE/GIT) Local repository is now empty. Reinitializing...')
  450. await this.init()
  451. }
  452. }