dev-to-git
Version: 
A CLI to keep your dev.to posts in sync from a GIT project, using the CI provider of your choice
165 lines • 8.15 kB
JavaScript
;
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var chalk_1 = require("chalk");
var commander_1 = require("commander");
var dotenv_1 = require("dotenv");
var fs_1 = require("fs");
var article_1 = require("./article");
var dev_to_git_interface_1 = require("./dev-to-git.interface");
var helpers_1 = require("./helpers");
exports.DEFAULT_CONFIG_PATH = './dev-to-git.json';
var repositoryRe = /.*\/(.*)\/(.*)\.git/;
var DevToGit = /** @class */ (function () {
    function DevToGit() {
        dotenv_1.default.config();
        var pkg = require('../package.json');
        commander_1.default
            .version(pkg.version)
            .arguments('[...files]')
            .option('--config <path>', "Pass custom path to .dev-to-git.json file", exports.DEFAULT_CONFIG_PATH)
            .option('--dev-to-token <token>', 'Token for publishing to dev.to', process.env.DEV_TO_GIT_TOKEN)
            .option('--repository-url <url>', 'Url of your repository you keep your articles in.')
            .option('--silent', "No console output")
            .parse(process.argv);
        var configuration = commander_1.default;
        this.configuration = configuration;
        this.logger = helpers_1.logBuilder(this.configuration);
        this.configuration.repository = this.parseRepository(commander_1.default.repositoryUrl) || this.extractRepository();
        if (!this.configuration.devToToken) {
            this.logger(chalk_1.default.red('DEV_TO_GIT_TOKEN environment variable, or --dev-to-token argument is required'));
            process.exit(1);
        }
    }
    DevToGit.prototype.parseRepository = function (repo) {
        if (!repo) {
            return null;
        }
        var match = repo.match(repositoryRe);
        if (!match) {
            return null;
        }
        return {
            username: match[1],
            name: match[2],
        };
    };
    DevToGit.prototype.extractRepository = function () {
        try {
            var packageJson = JSON.parse(fs_1.default.readFileSync('./package.json').toString());
            var repo = this.parseRepository(packageJson.repository.url);
            if (!repo) {
                throw Error();
            }
            return repo;
        }
        catch (error) {
            this.logger(chalk_1.default.red('If you do not specify --repository-url, you must have within your "package.json" a "repository" attribute which is an object and contains itself an attribute "url" like the following: https://github-gitlab-whatever.com/username/repository-name.git - this will be used to generate images links if necessary'));
            throw new Error();
        }
    };
    DevToGit.prototype.getConfigPath = function () {
        return this.configuration.config;
    };
    DevToGit.prototype.readConfigFile = function () {
        // @todo check structure of the object
        var _this = this;
        var articleConfigFiles = JSON.parse(fs_1.default.readFileSync(this.getConfigPath()).toString());
        return articleConfigFiles.map(function (articleConfigFile) { return (__assign({}, articleConfigFile, { repository: _this.configuration.repository })); });
    };
    DevToGit.prototype.publishArticles = function () {
        return __awaiter(this, void 0, void 0, function () {
            var articles, articlePublishedStatuses, _i, articles_1, articleConf, article, _a, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        articles = this.readConfigFile();
                        articlePublishedStatuses = [];
                        _i = 0, articles_1 = articles;
                        _c.label = 1;
                    case 1:
                        if (!(_i < articles_1.length)) return [3 /*break*/, 4];
                        articleConf = articles_1[_i];
                        article = new article_1.Article(articleConf, this.configuration.devToToken);
                        _b = (_a = articlePublishedStatuses).push;
                        return [4 /*yield*/, article.publishArticle()];
                    case 2:
                        _b.apply(_a, [_c.sent()]);
                        _c.label = 3;
                    case 3:
                        _i++;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/, articlePublishedStatuses];
                }
            });
        });
    };
    return DevToGit;
}());
exports.DevToGit = DevToGit;
// @todo move to main file?
var devToGit = new DevToGit();
devToGit
    .publishArticles()
    .then(function (articles) { return ({ articles: articles, text: helpers_1.formatArticlePublishedStatuses(articles) }); })
    .then(function (res) {
    devToGit.logger(res.text);
    res.articles.forEach(function (article) {
        if (article.updateStatus === dev_to_git_interface_1.UpdateStatus.ERROR ||
            article.updateStatus === dev_to_git_interface_1.UpdateStatus.FAILED_TO_EXTRACT_FRONT_MATTER) {
            // if there's been at least one error, exit and fail
            process.exit(1);
        }
    });
})
    .catch(function (error) {
    devToGit.logger(chalk_1.default.red("An error occurred while publishing the articles"));
    console.error(error);
    process.exit(1);
});
//# sourceMappingURL=dev-to-git.js.map