You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

444 lines
16 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  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. console.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('://', `://${this.config.basicUsername}:${this.config.basicPassword}@`)
  81. } else {
  82. originUrl = `https://${this.config.basicUsername}:${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 fPath = path.join(this.repoPath, f.file)
  129. let fStats = { size: 0 }
  130. try {
  131. fStats = await fs.stat(fPath)
  132. } catch (err) {
  133. if (err.code !== 'ENOENT') {
  134. WIKI.logger.warn(`(STORAGE/GIT) Failed to access file ${f.file}! Skipping...`)
  135. continue
  136. }
  137. }
  138. filesToProcess.push({
  139. ...f,
  140. file: {
  141. path: fPath,
  142. stats: fStats
  143. },
  144. relPath: f.file
  145. })
  146. }
  147. await this.processFiles(filesToProcess, rootUser)
  148. }
  149. }
  150. },
  151. /**
  152. * Process Files
  153. *
  154. * @param {Array<String>} files Array of files to process
  155. */
  156. async processFiles(files, user) {
  157. for (const item of files) {
  158. const contentType = pageHelper.getContentType(item.relPath)
  159. const fileExists = await fs.pathExists(item.file)
  160. if (!item.binary && contentType) {
  161. // -> Page
  162. if (!fileExists && item.deletions > 0 && item.insertions === 0) {
  163. // Page was deleted by git, can safely mark as deleted in DB
  164. WIKI.logger.info(`(STORAGE/GIT) Page marked as deleted: ${item.relPath}`)
  165. const contentPath = pageHelper.getPagePath(item.relPath)
  166. await WIKI.models.pages.deletePage({
  167. path: contentPath.path,
  168. locale: contentPath.locale,
  169. skipStorage: true
  170. })
  171. continue
  172. }
  173. try {
  174. await commonDisk.processPage({
  175. user,
  176. relPath: item.relPath,
  177. fullPath: this.repoPath,
  178. contentType: contentType,
  179. moduleName: 'GIT'
  180. })
  181. } catch (err) {
  182. WIKI.logger.warn(`(STORAGE/GIT) Failed to process ${item.relPath}`)
  183. WIKI.logger.warn(err)
  184. }
  185. } else {
  186. // -> Asset
  187. if (!fileExists && ((item.before > 0 && item.after === 0) || (item.deletions > 0 && item.insertions === 0))) {
  188. // Asset was deleted by git, can safely mark as deleted in DB
  189. WIKI.logger.info(`(STORAGE/GIT) Asset marked as deleted: ${item.relPath}`)
  190. const fileHash = assetHelper.generateHash(item.relPath)
  191. const assetToDelete = await WIKI.models.assets.query().findOne({ hash: fileHash })
  192. if (assetToDelete) {
  193. await WIKI.models.knex('assetData').where('id', assetToDelete.id).del()
  194. await WIKI.models.assets.query().deleteById(assetToDelete.id)
  195. await assetToDelete.deleteAssetCache()
  196. } else {
  197. WIKI.logger.info(`(STORAGE/GIT) Asset was not found in the DB, nothing to delete: ${item.relPath}`)
  198. }
  199. continue
  200. }
  201. try {
  202. await commonDisk.processAsset({
  203. user,
  204. relPath: item.relPath,
  205. file: item.file,
  206. contentType: contentType,
  207. moduleName: 'GIT'
  208. })
  209. } catch (err) {
  210. WIKI.logger.warn(`(STORAGE/GIT) Failed to process asset ${item.relPath}`)
  211. WIKI.logger.warn(err)
  212. }
  213. }
  214. }
  215. },
  216. /**
  217. * CREATE
  218. *
  219. * @param {Object} page Page to create
  220. */
  221. async created(page) {
  222. WIKI.logger.info(`(STORAGE/GIT) Committing new file [${page.localeCode}] ${page.path}...`)
  223. let fileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
  224. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  225. fileName = `${page.localeCode}/${fileName}`
  226. }
  227. const filePath = path.join(this.repoPath, fileName)
  228. await fs.outputFile(filePath, page.injectMetadata(), 'utf8')
  229. await this.git.add(`./${fileName}`)
  230. await this.git.commit(`docs: create ${page.path}`, fileName, {
  231. '--author': `"${page.authorName} <${page.authorEmail}>"`
  232. })
  233. },
  234. /**
  235. * UPDATE
  236. *
  237. * @param {Object} page Page to update
  238. */
  239. async updated(page) {
  240. WIKI.logger.info(`(STORAGE/GIT) Committing updated file [${page.localeCode}] ${page.path}...`)
  241. let fileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
  242. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  243. fileName = `${page.localeCode}/${fileName}`
  244. }
  245. const filePath = path.join(this.repoPath, fileName)
  246. await fs.outputFile(filePath, page.injectMetadata(), 'utf8')
  247. await this.git.add(`./${fileName}`)
  248. await this.git.commit(`docs: update ${page.path}`, fileName, {
  249. '--author': `"${page.authorName} <${page.authorEmail}>"`
  250. })
  251. },
  252. /**
  253. * DELETE
  254. *
  255. * @param {Object} page Page to delete
  256. */
  257. async deleted(page) {
  258. WIKI.logger.info(`(STORAGE/GIT) Committing removed file [${page.localeCode}] ${page.path}...`)
  259. let fileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
  260. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  261. fileName = `${page.localeCode}/${fileName}`
  262. }
  263. await this.git.rm(`./${fileName}`)
  264. await this.git.commit(`docs: delete ${page.path}`, fileName, {
  265. '--author': `"${page.authorName} <${page.authorEmail}>"`
  266. })
  267. },
  268. /**
  269. * RENAME
  270. *
  271. * @param {Object} page Page to rename
  272. */
  273. async renamed(page) {
  274. WIKI.logger.info(`(STORAGE/GIT) Committing file move from [${page.localeCode}] ${page.path} to [${page.destinationLocaleCode}] ${page.destinationPath}...`)
  275. let sourceFilePath = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
  276. let destinationFilePath = `${page.destinationPath}.${pageHelper.getFileExtension(page.contentType)}`
  277. if (WIKI.config.lang.namespacing) {
  278. if (WIKI.config.lang.code !== page.localeCode) {
  279. sourceFilePath = `${page.localeCode}/${sourceFilePath}`
  280. }
  281. if (WIKI.config.lang.code !== page.destinationLocaleCode) {
  282. destinationFilePath = `${page.destinationLocaleCode}/${destinationFilePath}`
  283. }
  284. }
  285. await this.git.mv(`./${sourceFilePath}`, `./${destinationFilePath}`)
  286. await this.git.commit(`docs: rename ${page.path} to ${page.destinationPath}`, [sourceFilePath, destinationFilePath], {
  287. '--author': `"${page.moveAuthorName} <${page.moveAuthorEmail}>"`
  288. })
  289. },
  290. /**
  291. * ASSET UPLOAD
  292. *
  293. * @param {Object} asset Asset to upload
  294. */
  295. async assetUploaded (asset) {
  296. WIKI.logger.info(`(STORAGE/GIT) Committing new file ${asset.path}...`)
  297. const filePath = path.join(this.repoPath, asset.path)
  298. await fs.outputFile(filePath, asset.data, 'utf8')
  299. await this.git.add(`./${asset.path}`)
  300. await this.git.commit(`docs: upload ${asset.path}`, asset.path, {
  301. '--author': `"${asset.authorName} <${asset.authorEmail}>"`
  302. })
  303. },
  304. /**
  305. * ASSET DELETE
  306. *
  307. * @param {Object} asset Asset to upload
  308. */
  309. async assetDeleted (asset) {
  310. WIKI.logger.info(`(STORAGE/GIT) Committing removed file ${asset.path}...`)
  311. await this.git.rm(`./${asset.path}`)
  312. await this.git.commit(`docs: delete ${asset.path}`, asset.path, {
  313. '--author': `"${asset.authorName} <${asset.authorEmail}>"`
  314. })
  315. },
  316. /**
  317. * ASSET RENAME
  318. *
  319. * @param {Object} asset Asset to upload
  320. */
  321. async assetRenamed (asset) {
  322. WIKI.logger.info(`(STORAGE/GIT) Committing file move from ${asset.path} to ${asset.destinationPath}...`)
  323. await this.git.mv(`./${asset.path}`, `./${asset.destinationPath}`)
  324. await this.git.commit(`docs: rename ${asset.path} to ${asset.destinationPath}`, [asset.path, asset.destinationPath], {
  325. '--author': `"${asset.moveAuthorName} <${asset.moveAuthorEmail}>"`
  326. })
  327. },
  328. /**
  329. * HANDLERS
  330. */
  331. async importAll() {
  332. WIKI.logger.info(`(STORAGE/GIT) Importing all content from local Git repo to the DB...`)
  333. const rootUser = await WIKI.models.users.getRootUser()
  334. await pipeline(
  335. klaw(this.repoPath, {
  336. filter: (f) => {
  337. return !_.includes(f, '.git')
  338. }
  339. }),
  340. new stream.Transform({
  341. objectMode: true,
  342. transform: async (file, enc, cb) => {
  343. const relPath = file.path.substr(this.repoPath.length + 1)
  344. if (file.stats.size < 1) {
  345. // Skip directories and zero-byte files
  346. return cb()
  347. } else if (relPath && relPath.length > 3) {
  348. WIKI.logger.info(`(STORAGE/GIT) Processing ${relPath}...`)
  349. await this.processFiles([{
  350. user: rootUser,
  351. relPath,
  352. file,
  353. deletions: 0,
  354. insertions: 0
  355. }], rootUser)
  356. }
  357. cb()
  358. }
  359. })
  360. )
  361. commonDisk.clearFolderCache()
  362. WIKI.logger.info('(STORAGE/GIT) Import completed.')
  363. },
  364. async syncUntracked() {
  365. WIKI.logger.info(`(STORAGE/GIT) Adding all untracked content...`)
  366. // -> Pages
  367. await pipeline(
  368. WIKI.models.knex.column('path', 'localeCode', 'title', 'description', 'contentType', 'content', 'isPublished', 'updatedAt').select().from('pages').where({
  369. isPrivate: false
  370. }).stream(),
  371. new stream.Transform({
  372. objectMode: true,
  373. transform: async (page, enc, cb) => {
  374. let fileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
  375. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  376. fileName = `${page.localeCode}/${fileName}`
  377. }
  378. WIKI.logger.info(`(STORAGE/GIT) Adding page ${fileName}...`)
  379. const filePath = path.join(this.repoPath, fileName)
  380. await fs.outputFile(filePath, pageHelper.injectPageMetadata(page), 'utf8')
  381. await this.git.add(`./${fileName}`)
  382. cb()
  383. }
  384. })
  385. )
  386. // -> Assets
  387. const assetFolders = await WIKI.models.assetFolders.getAllPaths()
  388. await pipeline(
  389. WIKI.models.knex.column('filename', 'folderId', 'data').select().from('assets').join('assetData', 'assets.id', '=', 'assetData.id').stream(),
  390. new stream.Transform({
  391. objectMode: true,
  392. transform: async (asset, enc, cb) => {
  393. const filename = (asset.folderId && asset.folderId > 0) ? `${_.get(assetFolders, asset.folderId)}/${asset.filename}` : asset.filename
  394. WIKI.logger.info(`(STORAGE/GIT) Adding asset ${filename}...`)
  395. await fs.outputFile(path.join(this.repoPath, filename), asset.data)
  396. await this.git.add(`./${filename}`)
  397. cb()
  398. }
  399. })
  400. )
  401. await this.git.commit(`docs: add all untracked content`)
  402. WIKI.logger.info('(STORAGE/GIT) All content is now tracked.')
  403. }
  404. }