all files / lib/remote/ gitlab.js

93.02% Statements 80/86
70% Branches 14/20
100% Functions 21/21
92.94% Lines 79/85
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169                                                                              14× 14× 14×   14×   14× 14×       13×       13×         12× 12×   12×   12× 12× 12×         12×     12×                                   14× 14× 14× 14×         14×   14×     13×   13×   13×          
'use strict';
 
var path = require('path');
var http = require('http');
var https = require('https');
var url = require('url');
 
var _ = require('lodash');
var fs = require('graceful-fs');
var gitlab = require('gitlab');
var Promise = require('bluebird');
var semver = require('semver');
var ProgressBar = require('progress');
 
var fecom = require('../fecom');
 
var GitlabRepo = function () {
  this.gitlab = {};
  this.repo = null;
};
 
GitlabRepo.prototype = {
  constructor: GitlabRepo,
  initialize: function () {
    var self = this;
    self.gitlab.token = fecom.profile.token;
    self.gitlab = gitlab({
      token: fecom.profile.token,
      url: fecom.config.domain + '/api/v3'
    });
    self.repo = self.gitlab.projects.repository;
  },
  getArchive: function (namespace, projectName, tagName) {
    var archiveUrl = fecom.config.domain + '/' + namespace + '/' + projectName + '/repository/archive.zip?ref=' + tagName + '&private_token=' + fecom.profile.token;
    var prefix = namespace + '/' + projectName + '-' + tagName;
    var archivePath = path.join(fecom.tmpDir, prefix + '-archive.zip');
    archiveUrl = url.parse(archiveUrl);
    var client = ('http:' === archiveUrl.protocol ? http : https);
    var semantic = fecom.stringify({
      name: projectName,
      owner: namespace,
      version: tagName
    });
 
    return new Promise(function (resolve) {
      // fecom.logger.info('Begin to download ' + specified);
      // fecom.logger.info(archiveUrl.href);
      var req = client.request(archiveUrl);
      req.end();
      req.on('response', function (res) {
        var dirname = path.join(fecom.tmpDir, namespace);
        var contentLength = res.headers['content-length'] >> 0;
        var bar = new ProgressBar(fecom.i18n('DOWNLOADING_COMPONENT', semantic), {
          complete: '=',
          incomplete: ' ',
          width: 20,
          total: contentLength
        });
 
        Iif (!fs.existsSync(dirname)) {
          fs.mkdirSync(dirname);
        }
 
        var stream = fs.createWriteStream(archivePath);
        res.on('data', function (chunk) {
          bar.tick(chunk.length);
          stream.write(chunk);
        });
        res.on('end', function () {
          stream.on('finish', function () {
            // fecom.logger.info('Finish downloading ' + prefix);
            resolve(archivePath);
          });
          stream.end();
        });
      });
    });
 
  },
  validate: function (namespace, projectName, version) {
    var self = this;
    var latestTag = '';
    var promise = version ? fecom.async(version) : self.getLatestTag(namespace, projectName).then(function (tag) { return tag.name; });
 
    return promise
      .then(function (tagName) {
        latestTag = tagName;
        return self.getComponentJson(namespace, projectName, tagName);
      })
      .then(function (json) {
 
        Iif (json.version !== latestTag) {
          return null;
        }
 
        return json;
      });
  },
  getDependencies: function (namespace, projectName, version) {
    // Get dependencies
    var self = this;
    var node = {};
 
    return self.validate(namespace, projectName, version)
      .then(function (json) {
        json.dependencies = json.dependencies || [];
        version = version || json.version;
        node.name = fecom.stringify({
          name: projectName,
          owner: namespace,
          version: version
        });
        node.dependencies = json.dependencies.map(function (specified) {
          return fecom.stringify(fecom.parse(specified));
        });
 
        return node;
      });
  },
  getLatestTag: function (namespace, projectName) {
    var self = this;
    return new Promise(function (resolve, reject) {
      var projectId = namespace + '/' + projectName;
      self.repo.listTags(projectId, function (tags) {
        var latest = {};
 
        Iif (!tags) {
          reject(new Error('Repository not found'));
          return false;
        }
 
        Iif (tags && !tags.length) {
          reject(new Error('Component tags not found in ' + projectId));
          return false;
        }
 
        latest = _(tags).sortBy('commit.committed_date').last();
 
        return resolve(latest);
      });
    });
  },
  getComponentJson: function (namespace, projectName, tagName) {
    var self = this;
    return new Promise(function (resolve, reject) {
      var projectId = namespace + '/' + projectName;
      self.repo.showFile({
        projectId: projectId,
        ref: 'tags/' + tagName,
        file_path: 'component.json'
      }, function (file) {
        var content, json;
 
        if (!file) {
          reject(new Error('"component.json" not found in ' + projectId));
          return false;
        }
 
        content = (new Buffer(file.content, 'base64')).toString();
 
        json = JSON.parse(content);
 
        resolve(json);
      });
    });
  }
};
 
module.exports = new GitlabRepo();