Skip to content

Commit

Permalink
New: adds assets (closes #12)
Browse files Browse the repository at this point in the history
  • Loading branch information
pustovitDmytro committed May 7, 2021
1 parent 58d2b2a commit 95ee7a7
Show file tree
Hide file tree
Showing 9 changed files with 403 additions and 68 deletions.
338 changes: 282 additions & 56 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,9 @@
"uuid": "^8.0.0"
},
"dependencies": {
"archiver": "^5.3.0",
"base-api-client": "1.2.0",
"form-data": "^4.0.0",
"git-url-parse": "11.4.4",
"livr": "2.3.3",
"livr-extra-rules": "1.2.1",
Expand Down
5 changes: 2 additions & 3 deletions src/success.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ import { getVariables } from './utils';

export default async function success(pluginConfig, { logger, nextRelease, options, branch }) {
if (!this.verified) throw new VERIFICATION_MISSED('success');
const { chats, botID, botToken, templates } = this.verified;
const { chats, botID, botToken, templates, assets } = this.verified;
const telegram = new Telegram(botID, botToken, chats);
const variables = getVariables({ verified: this.verified, nextRelease, options, branch });


await telegram.send(templates.success, variables);
await telegram.send(templates.success, variables, assets);

logger.log('Notifications has sent successfully');
}
Expand Down
29 changes: 26 additions & 3 deletions src/telegram/Telegram.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,28 @@

import { fill } from 'myrmidon';
import fs from 'fs';
import { Stream } from 'stream';
import { fill, isArray } from 'myrmidon';
import archiver from 'archiver';
import Api from './TelegramAPI';

function dumpChat(chat) {
return chat.title || chat.username;
}

function getArchiveStream(patterns, root) {
const archive = archiver('zip', { zlib: { level: 9 } });
const streamPassThrough = new Stream.PassThrough();

patterns.forEach(item => {
archive.glob(item, { cwd: root });
});

archive.pipe(streamPassThrough);
archive.finalize();

return streamPassThrough;
}

export default class Telegram {
constructor(botId, dotToken, chats) {
this.api = new Api(botId, dotToken);
Expand All @@ -16,8 +33,14 @@ export default class Telegram {
const html = fill(template, variables);
const promises = this.chats.map(async chat => {
await this.api.sendMessage(chat, html);
await Promise.all(files.map(async filePath => {
await this.api.sendFile(chat, filePath);
await Promise.all(files.map(async file => {
const stream = file.glob
? getArchiveStream(file.glob, file.rootDir)
: fs.createReadStream(file.path);

if (file.name) stream.path = file.name;

await this.api.sendFile(chat, stream);
}));
});

Expand Down
14 changes: 10 additions & 4 deletions src/telegram/TelegramAPI.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import BaseAPi from 'base-api-client';
import FormData from 'form-data';

export default class TelegramAPI extends BaseAPi {
constructor(id, token) {
Expand All @@ -18,10 +19,15 @@ export default class TelegramAPI extends BaseAPi {
});
}

sendFile(chatId, fileId) {
return this.post('sendDocument', {
'document' : fileId,
'chat_id' : chatId
sendFile(chatId, stream) {
const form = new FormData();

form.append('document', stream, { filepath: stream.path });
form.append('chat_id', chatId);

return this.post('sendDocument', form, {
headers : form.getHeaders(),
responseType : 'stream'
});
}

Expand Down
17 changes: 16 additions & 1 deletion src/verifyConditions.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,24 @@ const rules = {
templates : [ 'required', { 'nested_object' : {
success : [ 'string', { default: success } ],
fail : [ 'string', { default: fail } ]
} } ]
} } ],
assets : [ { 'list_of' : { or : [
{ 'nested_object' : {
path : [ 'required', 'string' ],
name : [ 'string' ]
} },
{ 'nested_object' : {
glob : [ 'required', { 'list_of': 'string' } ],
name : [ 'required', 'string' ]
} }
] } } ]
};

export default async function verifyConditions(pluginConfig, { logger, cwd, env, options, branch }) {
// eslint-disable-next-line security/detect-non-literal-require
const info = require(path.resolve(cwd, 'package.json'));
const raw = {
assets : [],
...options,
...pluginConfig,
botID : env.TELEGRAM_BOT_ID,
Expand All @@ -44,6 +55,10 @@ export default async function verifyConditions(pluginConfig, { logger, cwd, env,
const chatTitles = await telegram.test();

logger.log(`Verified chats: ${chatTitles.join(', ')}`);
data.assets = data.assets.map(asset => asset.glob
? { ...asset, rootDir: data.rootDir }
: asset
);
this.verified = data;

return data;
Expand Down
5 changes: 4 additions & 1 deletion tests/mock.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ class MOCK_API extends API {
return axiosResponse({ username: 'thick' });
}

console.log(opts);
if (opts.url.match('sendDocument')) {
return axiosResponse();
}

throw new Error('unknown');
}

Expand Down
16 changes: 16 additions & 0 deletions tests/package/success.test.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import path from 'path';
import { assert } from 'chai';
import { _load } from '../entry';
import Test from '../Test';
Expand Down Expand Up @@ -37,6 +38,21 @@ test('Default template', async function () {
});
});

test('Positive: assets', async function () {
const assets = [
{ path: 'CHANGELOG.md' },
{ glob: [ 'templates/**' ], name: 'templates', rootDir: path.resolve(__dirname, '../../') }
];

const verified = { name: 'test-app', templates, chats: [ 1, 2 ], repository, assets };

await success.call(
{ verified },
null,
{ logger: console, nextRelease: { version: '1.0.2', type: 'patch' } }
);
});

test('Negative: missing verify', async function () {
const promise = success.call(
{},
Expand Down
45 changes: 45 additions & 0 deletions tests/package/verifyConditions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,51 @@ test('Positive: valid configuration', async function () {
assert.deepEqual(apiCall.data, { 'chat_id': 9 });
});

test('Positive: assets', async function () {
const context = {};
const assets = [
{ path: 'CHANGELOG.md' },
{ glob: [ 'reports/**' ], name: 'reports.zip' }
];

await verifyConditions.call(
context,
{ chats: [ 9 ], name: 'app', assets },
{
logger : console,
cwd : process.cwd(),
env : {
TELEGRAM_BOT_ID : 'avxuD60y',
TELEGRAM_BOT_TOKEN : 'gmWKbSq7yeq4Z'
},
options,
branch
}
);

assert.deepOwnInclude(context.verified, {
'botID' : 'avxuD60y',
'botToken' : 'gmWKbSq7yeq4Z',
'branch' : 'master',
'repository' : {
url : options.repositoryUrl,
protocol : 'https',
dropHTTPSAuth : true
},
'chats' : [ 9 ],
'name' : 'app',
'templates' : {
'fail' : 'An <b><i>error</i></b> occured while trying to publish the new version of <b>{name}</b>.\n<pre><code class="language-javascript">{error}</code></pre>',
'success' : "A <b><i>{release_type}</i></b> version of <a href='{repository_url}'>{name}</a> has been released. Current version is <b>{version}</b>"

},
assets : [
assets[0],
{ ...assets[1], rootDir: process.cwd() }
]
});
});


test('Negative: invalid chat', async function () {
const promise = verifyConditions.call(
Expand Down

0 comments on commit 95ee7a7

Please sign in to comment.