git.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. "use strict";
  2. var NodeGit = require("nodegit"),
  3. Promise = require('bluebird'),
  4. path = require('path'),
  5. os = require('os'),
  6. fs = Promise.promisifyAll(require("fs")),
  7. moment = require('moment'),
  8. _ = require('lodash');
  9. /**
  10. * Git Model
  11. */
  12. module.exports = {
  13. _git: null,
  14. _repo: {
  15. path: '',
  16. branch: 'master',
  17. exists: false,
  18. inst: null,
  19. sync: true
  20. },
  21. _signature: {
  22. name: 'Wiki',
  23. email: 'user@example.com'
  24. },
  25. _opts: {
  26. clone: {},
  27. push: {}
  28. },
  29. /**
  30. * Initialize Git model
  31. *
  32. * @param {Object} appconfig The application config
  33. * @return {Object} Git model instance
  34. */
  35. init(appconfig) {
  36. let self = this;
  37. //-> Build repository path
  38. if(_.isEmpty(appconfig.git.path) || appconfig.git.path === 'auto') {
  39. self._repo.path = path.join(ROOTPATH, 'repo');
  40. } else {
  41. self._repo.path = appconfig.git.path;
  42. }
  43. //-> Initialize repository
  44. self._initRepo(appconfig).then((repo) => {
  45. self._repo.inst = repo;
  46. if(self._repo.sync) {
  47. self.resync();
  48. }
  49. });
  50. // Define signature
  51. self._signature.name = appconfig.git.userinfo.name || 'Wiki';
  52. self._signature.email = appconfig.git.userinfo.email || 'user@example.com';
  53. return self;
  54. },
  55. /**
  56. * Initialize Git repository
  57. *
  58. * @param {Object} appconfig The application config
  59. * @return {Object} Promise
  60. */
  61. _initRepo(appconfig) {
  62. let self = this;
  63. winston.info('[GIT] Initializing Git repository...');
  64. //-> Check if path is accessible
  65. return fs.mkdirAsync(self._repo.path).catch((err) => {
  66. if(err.code !== 'EEXIST') {
  67. winston.error('Invalid Git repository path or missing permissions.');
  68. }
  69. }).then(() => {
  70. //-> Check if path already contains a git working folder
  71. return fs.statAsync(path.join(self._repo.path, '.git')).then((stat) => {
  72. self._repo.exists = stat.isDirectory();
  73. }).catch((err) => {
  74. self._repo.exists = false;
  75. });
  76. }).then(() => {
  77. //-> Init repository
  78. let repoInitOperation = null;
  79. self._repo.branch = appconfig.git.branch;
  80. self._repo.sync = appconfig.git.remote;
  81. self._opts.clone = self._generateCloneOptions(appconfig);
  82. self._opts.push = self._generatePushOptions(appconfig);
  83. if(self._repo.exists) {
  84. winston.info('[GIT] Using existing repository...');
  85. repoInitOperation = NodeGit.Repository.open(self._repo.path);
  86. } else if(appconfig.git.remote) {
  87. winston.info('[GIT] Cloning remote repository for first time...');
  88. repoInitOperation = NodeGit.Clone(appconfig.git.url, self._repo.path, self._opts.clone);
  89. } else {
  90. winston.info('[GIT] Using offline local repository...');
  91. repoInitOperation = NodeGit.Repository.init(self._repo.path, 0);
  92. }
  93. return repoInitOperation;
  94. }).catch((err) => {
  95. winston.error('Unable to open or clone Git repository!');
  96. winston.error(err);
  97. }).then((repo) => {
  98. if(self._repo.sync) {
  99. NodeGit.Remote.setPushurl(repo, 'origin', appconfig.git.url);
  100. }
  101. return repo;
  102. winston.info('[GIT] Git repository is now ready.');
  103. });
  104. },
  105. /**
  106. * Generate Clone Options object
  107. *
  108. * @param {Object} appconfig The application configuration
  109. * @return {Object} CloneOptions object
  110. */
  111. _generateCloneOptions(appconfig) {
  112. let cloneOptions = new NodeGit.CloneOptions();
  113. cloneOptions.fetchOpts = this._generateFetchOptions(appconfig);
  114. return cloneOptions;
  115. },
  116. _generateFetchOptions(appconfig) {
  117. let fetchOptions = new NodeGit.FetchOptions();
  118. fetchOptions.callbacks = this._generateRemoteCallbacks(appconfig);
  119. return fetchOptions;
  120. },
  121. _generatePushOptions(appconfig) {
  122. let pushOptions = new NodeGit.PushOptions();
  123. pushOptions.callbacks = this._generateRemoteCallbacks(appconfig);
  124. return pushOptions;
  125. },
  126. _generateRemoteCallbacks(appconfig) {
  127. let remoteCallbacks = new NodeGit.RemoteCallbacks();
  128. let credFunc = this._generateCredentials(appconfig);
  129. remoteCallbacks.credentials = () => { return credFunc; };
  130. remoteCallbacks.transferProgress = _.noop;
  131. if(os.type() === 'Darwin') {
  132. remoteCallbacks.certificateCheck = () => { return 1; }; // Bug in OS X, bypass certs check workaround
  133. } else {
  134. remoteCallbacks.certificateCheck = _.noop;
  135. }
  136. return remoteCallbacks;
  137. },
  138. _generateCredentials(appconfig) {
  139. let cred = null;
  140. switch(appconfig.git.auth.type) {
  141. case 'basic':
  142. cred = NodeGit.Cred.userpassPlaintextNew(
  143. appconfig.git.auth.user,
  144. appconfig.git.auth.pass
  145. );
  146. break;
  147. case 'oauth':
  148. cred = NodeGit.Cred.userpassPlaintextNew(
  149. appconfig.git.auth.token,
  150. "x-oauth-basic"
  151. );
  152. break;
  153. case 'ssh':
  154. cred = NodeGit.Cred.sshKeyNew(
  155. appconfig.git.auth.user,
  156. appconfig.git.auth.publickey,
  157. appconfig.git.auth.privatekey,
  158. appconfig.git.auth.passphrase
  159. );
  160. break;
  161. default:
  162. cred = NodeGit.Cred.defaultNew();
  163. break;
  164. }
  165. return cred;
  166. },
  167. resync() {
  168. let self = this;
  169. // Fetch
  170. return self._repo.inst.fetch('origin', self._opts.clone.fetchOpts)
  171. .catch((err) => {
  172. winston.error('Unable to fetch from git origin!' + err);
  173. })
  174. // Merge
  175. .then(() => {
  176. return self._repo.inst.mergeBranches(self._repo.branch, 'origin/' + self._repo.branch);
  177. })
  178. .catch((err) => {
  179. winston.error('Unable to merge from remote head!' + err);
  180. })
  181. // Push
  182. .then(() => {
  183. return self._repo.inst.getRemote('origin').then((remote) => {
  184. // Get modified files
  185. return self._repo.inst.refreshIndex().then((index) => {
  186. return self._repo.inst.getStatus().then(function(arrayStatusFile) {
  187. let addOp = [];
  188. // Add to next commit
  189. _.forEach(arrayStatusFile, (v) => {
  190. addOp.push(arrayStatusFile[0].path());
  191. });
  192. console.log('DUDE1');
  193. // Create Commit
  194. let sig = NodeGit.Signature.create(self._signature.name, self._signature.email, moment().utc().unix(), 0);
  195. return self._repo.inst.createCommitOnHead(addOp, sig, sig, "Wiki Sync").then(() => {
  196. console.log('DUDE2');
  197. return remote.connect(NodeGit.Enums.DIRECTION.PUSH, self._opts.push.callbacks).then(() => {
  198. console.log('DUDE3');
  199. // Push to remote
  200. return remote.push( ["refs/heads/master:refs/heads/master"], self._opts.push).then((errNum) => {
  201. console.log('DUDE' + errNum);
  202. }).catch((err) => {
  203. console.log(err);
  204. });
  205. });
  206. });
  207. });
  208. })
  209. /**/
  210. });
  211. }).catch((err) => {
  212. winston.error('Unable to push to git origin!' + err);
  213. });
  214. }
  215. };