storage.js 15 KB

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