storage.js 19 KB

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