Skip to content

Commit

Permalink
#4 - continue main
Browse files Browse the repository at this point in the history
  • Loading branch information
moshfeu committed Nov 2, 2018
1 parent a9c5707 commit 94b2283
Show file tree
Hide file tree
Showing 6 changed files with 161 additions and 58 deletions.
37 changes: 37 additions & 0 deletions __mocks__/simple-git/promise.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const simpleGit = require('simple-git/promise');
const {readdirSync} = require('fs');

let sg;
const listeners = [];

module.exports = (localFolder) => {
if (localFolder) {
listeners.forEach(listener => {
listener(localFolder);
});
sg = simpleGit(localFolder);
}
return {
clone: async () => {
await sg.init();
},
add: () => {
// console.log('mock add!!!');
},
addConfig: () => {
// console.log('mock addConfig!');
},
status: () => {
return sg.status();
},
commit: async () => {
// console.log('mock commit', readdirSync(localFolder));
},
push: () => {
// console.log('mock push');
},
_dispose: () => {
sg = null;
}
}
}
122 changes: 72 additions & 50 deletions __tests__/server.spec.ts
Original file line number Diff line number Diff line change
@@ -1,68 +1,90 @@
import {get, Server} from 'http';
// tslint:disable-next-line:no-implicit-dependencies
import axios from 'axios';
// tslint:disable-next-line:no-submodule-imports
import * as simpleGit from 'simple-git/promise';
import {startServer} from '../src/server';

jest.mock('simple-git/promise');

describe('main', () => {
const port = 15523;
const baseUrl = `http://localhost:${port}`;
let server: Server;
let port;
let baseUrl;
let server;
let sg;

beforeEach(() => {
beforeEach(async () => {
try {
server = startServer(port);
// tslint:disable
port = 3000 + Math.ceil(Math.random() * 1000);
// tslint:enable
process.env.PORT = port;
baseUrl = `http://localhost:${port}`;
server = await startServer();
sg = simpleGit();

return server;
} catch (error) {
console.log(error, `can't start the server`);
}
});

afterEach(() => {
server.close(() => {
console.log('server closed');
});
afterEach(async () => {
server.close();
sg._dispose();
})

it('GET /', done => {
get(baseUrl, res => {
expect(res.statusCode).toBe(200);
// tslint:disable:mocha-unneeded-done
it('GET /', async (done) => {
const res = await axios(baseUrl);
expect(res.status).toBe(200);
expect(res.data).toBe('Hello World!');
done();
});

describe('POST /commit', () => {
// tslint:disable-next-line:mocha-unneeded-done
it('complete payload', async (done) => {
const res = await axios({
url: `http://localhost:${port}/commit`,
method: 'POST',
data: payload
});
expect(res.status).toBe(200);
expect(res.data).toBe('done');
const gitStatus = await sg.status();
expect(
gitStatus.files.map(file => file.path)
).toEqual(
payload.files.map(file => file.path)
);
done();
});
});

// it('POST /commit', done => {
// // try {

// const req = request({host: 'localhost', port: port, method: 'POST', path: '/commit'}, res => {
// console.log('res!!', res);
// res.on('data', chunk => {
// console.log('chunk', chunk);
// expect(chunk).toBe('done');
// done();
// });
// });

// // console.log('req', req);

// req.write(JSON.stringify({
// "remoteRepo": "moshfeu/commit-bot-test",
// "token": "7cb950575b914d7c36a8de37d9db056671e92788",
// "commitMessage": "yet another commit",
// "files": [
// {
// "path": "folder1/folder2/file3.js",
// "content": "alert('blabla123')"
// },
// {
// "path": "folder1/folder3/file4.ts",
// "content": "import * as path from 'path';"
// }
// ]
// }));
it('not complete payload', async (done) => {
const res = await axios({
url: `http://localhost:${port}/commit`,
method: 'POST',
validateStatus: () => true
});

// // console.log('req done');
// // } catch (error) {
// // console.log('error', error);
// // }
expect(res.status).toBe(500);
done();
});
});

// // expect(1).toBe(1);
// // done();
// });
});
const payload = {
"remoteRepo": "moshfeu/commit-bot-test",
"token": "7cb950575b914d7c36a8de37d9db056671e92788",
"commitMessage": "yet another commit",
"files": [
{
"path": "folder1/folder2/file3.js",
"content": "alert('blabla123')"
},
{
"path": "folder1/folder3/file4.ts",
"content": "import * as path from 'path';"
}
]
};
5 changes: 4 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ module.exports = {
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(js)x?$',
coverageDirectory: 'coverage',
collectCoverageFrom: [
'src/**/*.{js,jsx}',
'dist/src/**/*.{js,jsx}',
'!src/**/*.d.ts',
],
moduleNameMapper: {
"simple-git/promise": "<rootDir>/__mocks__/simple-git/promise.js"
}
};
30 changes: 30 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
"tslint": "~5.11.0",
"tslint-config-prettier": "1.15.0",
"tslint-microsoft-contrib": "~5.2.1",
"tsutils": "~3.0.0"
"tsutils": "~3.0.0",
"axios": "^0.18.0"
},
"scripts": {
"debug": "tsc | nodemon dist/src/main.js --nolazy --debug-brk=5858",
Expand Down
22 changes: 16 additions & 6 deletions src/server.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import * as bodyParser from 'body-parser';
import * as express from 'express';
import { readdirSync } from 'fs';
import {Server} from 'http';
import {join} from 'path';
// tslint:disable-next-line:no-submodule-imports
import * as simpleGit from 'simple-git/promise';
import{directory} from 'tempy';
import {directory} from 'tempy';
import {writeFileDeepSync} from './utils';

export function startServer(port = process.env.PORT || 3000): Server {
export function startServer(port = process.env.PORT || 3000): Promise<Server> {
const app = express();

app.use(bodyParser.json());
Expand All @@ -18,10 +17,16 @@ export function startServer(port = process.env.PORT || 3000): Server {
app.post('/commit', async (req, res) => {
const { remoteRepo, token, files, commitMessage } = req.body as {[key: string]: string | IFile[]};

const tempFolder = directory();
if (!remoteRepo || !token || !files || !commitMessage) {
res.status(500).send(`Payload isn't complete`);

return;
}

const tempFolder = directory();
const sg = simpleGit(tempFolder);
await sg.clone(`https://${token}@github.com/${remoteRepo}.git`, tempFolder);

(<IFile[]>files).forEach((file: IFile) => {
writeFileDeepSync(join(tempFolder, file.path), file.content);
});
Expand All @@ -30,13 +35,18 @@ export function startServer(port = process.env.PORT || 3000): Server {
await sg.addConfig('user.email', 'bot@spread-the-code.com');
await sg.addConfig('user.name', 'committer-bot');

await sg.commit(<string>commitMessage || 'unknow commit');
await sg.commit(<string>commitMessage);
await sg.push();

res.send('done');
});

return app.listen(port, () => console.log(`Example app listening on port ${port}!`))
return new Promise((resolve) => {
const server = app.listen(port, () => {
console.log(`Example app listening on port ${port}!`);
resolve(server);
});
})
}

interface IFile {
Expand Down

0 comments on commit 94b2283

Please sign in to comment.