Best JavaScript code snippet using qawolf
status-bar-tile-controller.test.js
Source:status-bar-tile-controller.test.js
1import fs from 'fs';2import path from 'path';3import React from 'react';4import until from 'test-until';5import {mount} from 'enzyme';6import {cloneRepository, buildRepository, buildRepositoryWithPipeline, setUpLocalAndRemoteRepositories} from '../helpers';7import {getTempDir} from '../../lib/helpers';8import Repository from '../../lib/models/repository';9import StatusBarTileController from '../../lib/controllers/status-bar-tile-controller';10import BranchView from '../../lib/views/branch-view';11import ChangedFilesCountView from '../../lib/views/changed-files-count-view';12import GithubTileView from '../../lib/views/github-tile-view';13describe('StatusBarTileController', function() {14 let atomEnvironment;15 let workspace, workspaceElement, commands, notificationManager, tooltips, confirm;16 beforeEach(function() {17 atomEnvironment = global.buildAtomEnvironment();18 workspace = atomEnvironment.workspace;19 commands = atomEnvironment.commands;20 notificationManager = atomEnvironment.notifications;21 tooltips = atomEnvironment.tooltips;22 confirm = sinon.stub(atomEnvironment, 'confirm');23 workspaceElement = atomEnvironment.views.getView(workspace);24 });25 afterEach(function() {26 atomEnvironment.destroy();27 });28 function buildApp(props) {29 return (30 <StatusBarTileController31 workspace={workspace}32 commands={commands}33 notificationManager={notificationManager}34 tooltips={tooltips}35 confirm={confirm}36 toggleGitTab={() => {}}37 toggleGithubTab={() => {}}38 {...props}39 />40 );41 }42 function getTooltipNode(wrapper, selector) {43 const ts = tooltips.findTooltips(wrapper.find(selector).getDOMNode());44 assert.lengthOf(ts, 1);45 ts[0].show();46 return ts[0].getTooltipElement();47 }48 async function mountAndLoad(app) {49 const wrapper = mount(app);50 await assert.async.isTrue(wrapper.update().find('.github-ChangedFilesCount').exists());51 return wrapper;52 }53 describe('branches', function() {54 it('indicates the current branch', async function() {55 const workdirPath = await cloneRepository('three-files');56 const repository = await buildRepository(workdirPath);57 const wrapper = await mountAndLoad(buildApp({repository}));58 assert.equal(wrapper.find(BranchView).prop('currentBranch').name, 'master');59 assert.lengthOf(wrapper.find(BranchView).find('.github-branch-detached'), 0);60 });61 it('styles a detached HEAD differently', async function() {62 const workdirPath = await cloneRepository('multiple-commits');63 const repository = await buildRepository(workdirPath);64 await repository.checkout('HEAD~2');65 const wrapper = await mountAndLoad(buildApp({repository}));66 assert.equal(wrapper.find(BranchView).prop('currentBranch').name, 'master~2');67 assert.lengthOf(wrapper.find(BranchView).find('.github-branch-detached'), 1);68 });69 describe('the branch menu', function() {70 function selectOption(tip, value) {71 const selects = Array.from(tip.getElementsByTagName('select'));72 assert.lengthOf(selects, 1);73 const select = selects[0];74 select.value = value;75 const event = new Event('change', {bubbles: true, cancelable: true});76 select.dispatchEvent(event);77 }78 describe('checking out an existing branch', function() {79 it('can check out existing branches with no conflicts', async function() {80 const workdirPath = await cloneRepository('three-files');81 const repository = await buildRepository(workdirPath);82 // create branch called 'branch'83 await repository.git.exec(['branch', 'branch']);84 const wrapper = await mountAndLoad(buildApp({repository}));85 const tip = getTooltipNode(wrapper, '.github-branch');86 const selectList = tip.querySelector('select');87 const branches = Array.from(tip.getElementsByTagName('option'), e => e.innerHTML);88 assert.deepEqual(branches, ['branch', 'master']);89 const branch0 = await repository.getCurrentBranch();90 assert.equal(branch0.getName(), 'master');91 assert.isFalse(branch0.isDetached());92 assert.equal(selectList.value, 'master');93 selectOption(tip, 'branch');94 assert.isTrue(selectList.hasAttribute('disabled'));95 await until(async () => {96 const branch1 = await repository.getCurrentBranch();97 return branch1.getName() === 'branch' && !branch1.isDetached();98 });99 await assert.async.equal(selectList.value, 'branch');100 await assert.async.isFalse(selectList.hasAttribute('disabled'));101 selectOption(tip, 'master');102 assert.isTrue(selectList.hasAttribute('disabled'));103 await until(async () => {104 const branch2 = await repository.getCurrentBranch();105 return branch2.getName() === 'master' && !branch2.isDetached();106 });107 await assert.async.equal(selectList.value, 'master');108 await assert.async.isFalse(selectList.hasAttribute('disabled'));109 });110 it('displays an error message if checkout fails', async function() {111 const {localRepoPath} = await setUpLocalAndRemoteRepositories('three-files');112 const repository = await buildRepositoryWithPipeline(localRepoPath, {confirm, notificationManager, workspace});113 await repository.git.exec(['branch', 'branch']);114 // create a conflict115 fs.writeFileSync(path.join(localRepoPath, 'a.txt'), 'a change');116 await repository.git.exec(['commit', '-a', '-m', 'change on master']);117 await repository.checkout('branch');118 fs.writeFileSync(path.join(localRepoPath, 'a.txt'), 'a change that conflicts');119 const wrapper = await mountAndLoad(buildApp({repository}));120 const tip = getTooltipNode(wrapper, BranchView);121 const selectList = tip.querySelector('select');122 const branch0 = await repository.getCurrentBranch();123 assert.equal(branch0.getName(), 'branch');124 assert.isFalse(branch0.isDetached());125 assert.equal(selectList.value, 'branch');126 sinon.stub(notificationManager, 'addError');127 selectOption(tip, 'master');128 assert.isTrue(selectList.hasAttribute('disabled'));129 await assert.async.equal(selectList.value, 'master');130 await until(() => {131 repository.refresh();132 return selectList.value === 'branch';133 });134 assert.isTrue(notificationManager.addError.called);135 assert.isFalse(selectList.hasAttribute('disabled'));136 const notificationArgs = notificationManager.addError.args[0];137 assert.equal(notificationArgs[0], 'Checkout aborted');138 assert.match(notificationArgs[1].description, /Local changes to the following would be overwritten/);139 });140 });141 describe('checking out newly created branches', function() {142 it('can check out newly created branches', async function() {143 const workdirPath = await cloneRepository('three-files');144 const repository = await buildRepositoryWithPipeline(workdirPath, {confirm, notificationManager, workspace});145 const wrapper = await mountAndLoad(buildApp({repository}));146 const tip = getTooltipNode(wrapper, BranchView);147 const selectList = tip.querySelector('select');148 const editor = tip.querySelector('atom-text-editor');149 const branches = Array.from(tip.querySelectorAll('option'), option => option.value);150 assert.deepEqual(branches, ['master']);151 const branch0 = await repository.getCurrentBranch();152 assert.equal(branch0.getName(), 'master');153 assert.isFalse(branch0.isDetached());154 assert.equal(selectList.value, 'master');155 tip.querySelector('button').click();156 assert.isTrue(selectList.className.includes('hidden'));157 assert.isFalse(tip.querySelector('.github-BranchMenuView-editor').className.includes('hidden'));158 tip.querySelector('atom-text-editor').getModel().setText('new-branch');159 tip.querySelector('button').click();160 assert.isTrue(editor.hasAttribute('readonly'));161 await until(async () => {162 const branch1 = await repository.getCurrentBranch();163 return branch1.getName() === 'new-branch' && !branch1.isDetached();164 });165 repository.refresh(); // clear cache manually, since we're not listening for file system events here166 await assert.async.equal(selectList.value, 'new-branch');167 await assert.async.isTrue(tip.querySelector('.github-BranchMenuView-editor').className.includes('hidden'));168 assert.isFalse(selectList.className.includes('hidden'));169 });170 it('displays an error message if branch already exists', async function() {171 const workdirPath = await cloneRepository('three-files');172 const repository = await buildRepositoryWithPipeline(workdirPath, {confirm, notificationManager, workspace});173 await repository.git.exec(['checkout', '-b', 'branch']);174 const wrapper = await mountAndLoad(buildApp({repository}));175 const tip = getTooltipNode(wrapper, BranchView);176 const createNewButton = tip.querySelector('button');177 sinon.stub(notificationManager, 'addError');178 const branches = Array.from(tip.getElementsByTagName('option'), option => option.value);179 assert.deepEqual(branches, ['branch', 'master']);180 const branch0 = await repository.getCurrentBranch();181 assert.equal(branch0.getName(), 'branch');182 assert.isFalse(branch0.isDetached());183 assert.equal(tip.querySelector('select').value, 'branch');184 createNewButton.click();185 tip.querySelector('atom-text-editor').getModel().setText('master');186 createNewButton.click();187 assert.isTrue(createNewButton.hasAttribute('disabled'));188 await assert.async.isTrue(notificationManager.addError.called);189 const notificationArgs = notificationManager.addError.args[0];190 assert.equal(notificationArgs[0], 'Cannot create branch');191 assert.match(notificationArgs[1].description, /already exists/);192 const branch1 = await repository.getCurrentBranch();193 assert.equal(branch1.getName(), 'branch');194 assert.isFalse(branch1.isDetached());195 assert.lengthOf(tip.querySelectorAll('.github-BranchMenuView-editor'), 1);196 assert.equal(tip.querySelector('atom-text-editor').getModel().getText(), 'master');197 assert.isFalse(createNewButton.hasAttribute('disabled'));198 });199 it('clears the new branch name after successful creation', async function() {200 const workdirPath = await cloneRepository('three-files');201 const repository = await buildRepositoryWithPipeline(workdirPath, {confirm, notificationManager, workspace});202 const wrapper = await mountAndLoad(buildApp({repository}));203 // Open the branch creator, type a branch name, and confirm branch creation.204 await wrapper.find('.github-BranchMenuView-button').simulate('click');205 wrapper.find('.github-BranchMenuView-editor atom-text-editor').getDOMNode().getModel()206 .setText('new-branch-name');207 await wrapper.find('.github-BranchMenuView-button').simulate('click');208 await until('branch creation completes', async () => {209 const b = await repository.getCurrentBranch();210 return b.getName() === 'new-branch-name' && !b.isDetached();211 });212 repository.refresh();213 await assert.async.isUndefined(214 wrapper.update().find('.github-BranchMenuView-editor atom-text-editor').prop('readonly'),215 );216 await wrapper.find('.github-BranchMenuView-button').simulate('click');217 assert.strictEqual(218 wrapper.find('.github-BranchMenuView-editor atom-text-editor').getDOMNode().getModel().getText(),219 '',220 );221 });222 });223 describe('with a detached HEAD', function() {224 it('includes the current describe output as a disabled option', async function() {225 const workdirPath = await cloneRepository('multiple-commits');226 const repository = await buildRepository(workdirPath);227 await repository.checkout('HEAD~2');228 const wrapper = await mountAndLoad(buildApp({repository}));229 const tip = getTooltipNode(wrapper, BranchView);230 assert.equal(tip.querySelector('select').value, 'detached');231 const option = tip.querySelector('option[value="detached"]');232 assert.equal(option.textContent, 'master~2');233 assert.isTrue(option.disabled);234 });235 });236 });237 });238 describe('pushing and pulling', function() {239 describe('status bar tile state', function() {240 describe('when there is no remote tracking branch', function() {241 let repository;242 let statusBarTile;243 beforeEach(async function() {244 const {localRepoPath} = await setUpLocalAndRemoteRepositories();245 repository = await buildRepository(localRepoPath);246 await repository.git.exec(['checkout', '-b', 'new-branch']);247 statusBarTile = await mountAndLoad(buildApp({repository}));248 sinon.spy(repository, 'fetch');249 sinon.spy(repository, 'push');250 sinon.spy(repository, 'pull');251 });252 it('gives the option to publish the current branch', function() {253 assert.equal(statusBarTile.find('.github-PushPull').text().trim(), 'Publish');254 });255 it('pushes the current branch when clicked', function() {256 statusBarTile.find('.github-PushPull').simulate('click');257 assert.isTrue(repository.push.called);258 });259 it('does nothing when clicked and currently pushing', async function() {260 repository.getOperationStates().setPushInProgress(true);261 await assert.async.strictEqual(statusBarTile.update().find('.github-PushPull').text().trim(), 'Pushing');262 statusBarTile.find('.github-PushPull').simulate('click');263 assert.isFalse(repository.fetch.called);264 assert.isFalse(repository.push.called);265 assert.isFalse(repository.pull.called);266 });267 });268 describe('when there is a remote with nothing to pull or push', function() {269 let repository;270 let statusBarTile;271 beforeEach(async function() {272 const {localRepoPath} = await setUpLocalAndRemoteRepositories();273 repository = await buildRepository(localRepoPath);274 statusBarTile = await mountAndLoad(buildApp({repository}));275 sinon.spy(repository, 'fetch');276 sinon.spy(repository, 'push');277 sinon.spy(repository, 'pull');278 });279 it('gives the option to fetch from remote', function() {280 assert.equal(statusBarTile.find('.github-PushPull').text().trim(), 'Fetch');281 });282 it('fetches from remote when clicked', function() {283 statusBarTile.find('.github-PushPull').simulate('click');284 assert.isTrue(repository.fetch.called);285 });286 it('does nothing when clicked and currently fetching', async function() {287 repository.getOperationStates().setFetchInProgress(true);288 await assert.async.strictEqual(statusBarTile.update().find('.github-PushPull').text().trim(), 'Fetching');289 statusBarTile.find('.github-PushPull').simulate('click');290 assert.isFalse(repository.fetch.called);291 assert.isFalse(repository.push.called);292 assert.isFalse(repository.pull.called);293 });294 });295 describe('when there is a remote and we are ahead', function() {296 let repository;297 let statusBarTile;298 beforeEach(async function() {299 const {localRepoPath} = await setUpLocalAndRemoteRepositories();300 repository = await buildRepository(localRepoPath);301 await repository.git.commit('new local commit', {allowEmpty: true});302 statusBarTile = await mountAndLoad(buildApp({repository}));303 sinon.spy(repository, 'fetch');304 sinon.spy(repository, 'push');305 sinon.spy(repository, 'pull');306 });307 it('gives the option to push with ahead count', function() {308 assert.equal(statusBarTile.find('.github-PushPull').text().trim(), 'Push 1');309 });310 it('pushes when clicked', function() {311 statusBarTile.find('.github-PushPull').simulate('click');312 assert.isTrue(repository.push.called);313 });314 it('does nothing when clicked and is currently pushing', async function() {315 repository.getOperationStates().setPushInProgress(true);316 await assert.async.strictEqual(statusBarTile.find('.github-PushPull').text().trim(), 'Pushing');317 statusBarTile.find('.github-PushPull').simulate('click');318 assert.isFalse(repository.fetch.called);319 assert.isFalse(repository.push.called);320 assert.isFalse(repository.pull.called);321 });322 });323 describe('when there is a remote and we are behind', function() {324 let repository;325 let statusBarTile;326 beforeEach(async function() {327 const {localRepoPath} = await setUpLocalAndRemoteRepositories();328 repository = await buildRepository(localRepoPath);329 await repository.git.exec(['reset', '--hard', 'HEAD~2']);330 statusBarTile = await mountAndLoad(buildApp({repository}));331 sinon.spy(repository, 'fetch');332 sinon.spy(repository, 'push');333 sinon.spy(repository, 'pull');334 });335 it('gives the option to pull with behind count', function() {336 assert.equal(statusBarTile.find('.github-PushPull').text().trim(), 'Pull 2');337 });338 it('pulls when clicked', function() {339 statusBarTile.find('.github-PushPull').simulate('click');340 assert.isTrue(repository.pull.called);341 });342 it('does nothing when clicked and is currently pulling', async function() {343 repository.getOperationStates().setPullInProgress(true);344 await assert.async.strictEqual(statusBarTile.update().find('.github-PushPull').text().trim(), 'Pulling');345 statusBarTile.find('.github-PushPull').simulate('click');346 assert.isFalse(repository.fetch.called);347 assert.isFalse(repository.push.called);348 assert.isFalse(repository.pull.called);349 });350 });351 describe('when there is a remote and we are ahead and behind', function() {352 let repository;353 let statusBarTile;354 beforeEach(async function() {355 const {localRepoPath} = await setUpLocalAndRemoteRepositories();356 repository = await buildRepository(localRepoPath);357 await repository.git.exec(['reset', '--hard', 'HEAD~2']);358 await repository.git.commit('new local commit', {allowEmpty: true});359 statusBarTile = await mountAndLoad(buildApp({repository}));360 sinon.spy(repository, 'fetch');361 sinon.spy(repository, 'push');362 sinon.spy(repository, 'pull');363 });364 it('gives the option to pull with ahead and behind count', function() {365 assert.equal(statusBarTile.find('.github-PushPull').text().trim(), '1 Pull 2');366 });367 it('pulls when clicked', function() {368 statusBarTile.find('.github-PushPull').simulate('click');369 assert.isTrue(repository.pull.called);370 assert.isFalse(repository.fetch.called);371 assert.isFalse(repository.push.called);372 });373 it('does nothing when clicked and is currently pulling', async function() {374 repository.getOperationStates().setPullInProgress(true);375 await assert.async.strictEqual(statusBarTile.update().find('.github-PushPull').text().trim(), 'Pulling');376 statusBarTile.find('.github-PushPull').simulate('click');377 assert.isFalse(repository.fetch.called);378 assert.isFalse(repository.push.called);379 assert.isFalse(repository.pull.called);380 });381 });382 describe('when there is a remote and we are detached HEAD', function() {383 let repository;384 let statusBarTile;385 beforeEach(async function() {386 const {localRepoPath} = await setUpLocalAndRemoteRepositories();387 repository = await buildRepository(localRepoPath);388 await repository.checkout('HEAD~2');389 statusBarTile = await mountAndLoad(buildApp({repository}));390 sinon.spy(repository, 'fetch');391 sinon.spy(repository, 'push');392 sinon.spy(repository, 'pull');393 });394 it('gives a hint that we are not on a branch', function() {395 assert.equal(statusBarTile.find('.github-PushPull').text().trim(), 'Not on branch');396 });397 it('does nothing when clicked', function() {398 statusBarTile.find('.github-PushPull').simulate('click');399 assert.equal(statusBarTile.find('.github-PushPull').text().trim(), 'Not on branch');400 assert.isFalse(repository.fetch.called);401 assert.isFalse(repository.push.called);402 assert.isFalse(repository.pull.called);403 });404 });405 describe('when there is no remote named "origin"', function() {406 let repository;407 let statusBarTile;408 beforeEach(async function() {409 const {localRepoPath} = await setUpLocalAndRemoteRepositories();410 repository = await buildRepository(localRepoPath);411 await repository.git.exec(['remote', 'remove', 'origin']);412 statusBarTile = await mountAndLoad(buildApp({repository}));413 sinon.spy(repository, 'fetch');414 sinon.spy(repository, 'push');415 sinon.spy(repository, 'pull');416 });417 it('gives that there is no remote', function() {418 assert.equal(statusBarTile.find('.github-PushPull').text().trim(), 'No remote');419 });420 it('does nothing when clicked', function() {421 statusBarTile.find('.github-PushPull').simulate('click');422 assert.equal(statusBarTile.find('.github-PushPull').text().trim(), 'No remote');423 assert.isFalse(repository.fetch.called);424 assert.isFalse(repository.push.called);425 assert.isFalse(repository.pull.called);426 });427 });428 });429 it('displays an error message if push fails', async function() {430 const {localRepoPath} = await setUpLocalAndRemoteRepositories();431 const repository = await buildRepositoryWithPipeline(localRepoPath, {confirm, notificationManager, workspace});432 await repository.git.exec(['reset', '--hard', 'HEAD~2']);433 await repository.git.commit('another commit', {allowEmpty: true});434 const wrapper = await mountAndLoad(buildApp({repository}));435 sinon.stub(notificationManager, 'addError');436 try {437 await wrapper.instance().push(await wrapper.instance().fetchData(repository))();438 } catch (e) {439 assert(e, 'is error');440 }441 await assert.async.isTrue(notificationManager.addError.called);442 const notificationArgs = notificationManager.addError.args[0];443 assert.equal(notificationArgs[0], 'Push rejected');444 assert.match(notificationArgs[1].description, /Try pulling before pushing/);445 });446 describe('fetch and pull commands', function() {447 it('fetches when github:fetch is triggered', async function() {448 const {localRepoPath} = await setUpLocalAndRemoteRepositories('multiple-commits', {remoteAhead: true});449 const repository = await buildRepository(localRepoPath);450 await mountAndLoad(buildApp({repository}));451 sinon.spy(repository, 'fetch');452 commands.dispatch(workspaceElement, 'github:fetch');453 assert.isTrue(repository.fetch.called);454 });455 it('pulls when github:pull is triggered', async function() {456 const {localRepoPath} = await setUpLocalAndRemoteRepositories('multiple-commits', {remoteAhead: true});457 const repository = await buildRepository(localRepoPath);458 await mountAndLoad(buildApp({repository}));459 sinon.spy(repository, 'pull');460 commands.dispatch(workspaceElement, 'github:pull');461 assert.isTrue(repository.pull.called);462 });463 it('pushes when github:push is triggered', async function() {464 const {localRepoPath} = await setUpLocalAndRemoteRepositories();465 const repository = await buildRepository(localRepoPath);466 await mountAndLoad(buildApp({repository}));467 sinon.spy(repository, 'push');468 commands.dispatch(workspaceElement, 'github:push');469 assert.isTrue(repository.push.calledWith('master', sinon.match({force: false, setUpstream: false})));470 });471 it('force pushes when github:force-push is triggered', async function() {472 const {localRepoPath} = await setUpLocalAndRemoteRepositories();473 const repository = await buildRepositoryWithPipeline(localRepoPath, {confirm, notificationManager, workspace});474 confirm.returns(0);475 await mountAndLoad(buildApp({repository}));476 sinon.spy(repository.git, 'push');477 commands.dispatch(workspaceElement, 'github:force-push');478 assert.equal(confirm.callCount, 1);479 await assert.async.isTrue(repository.git.push.calledWith('origin', 'master', sinon.match({force: true, setUpstream: false})));480 await assert.async.isFalse(repository.getOperationStates().isPushInProgress());481 });482 it('displays a warning notification when pull results in merge conflicts', async function() {483 const {localRepoPath} = await setUpLocalAndRemoteRepositories('multiple-commits', {remoteAhead: true});484 fs.writeFileSync(path.join(localRepoPath, 'file.txt'), 'apple');485 const repository = await buildRepositoryWithPipeline(localRepoPath, {confirm, notificationManager, workspace});486 await repository.git.exec(['commit', '-am', 'Add conflicting change']);487 const wrapper = await mountAndLoad(buildApp({repository}));488 sinon.stub(notificationManager, 'addWarning');489 try {490 await wrapper.instance().pull(await wrapper.instance().fetchData(repository))();491 } catch (e) {492 assert(e, 'is error');493 }494 repository.refresh();495 await assert.async.isTrue(notificationManager.addWarning.called);496 const notificationArgs = notificationManager.addWarning.args[0];497 assert.equal(notificationArgs[0], 'Merge conflicts');498 assert.match(notificationArgs[1].description, /Your local changes conflicted with changes made on the remote branch./);499 assert.isTrue(await repository.isMerging());500 });501 });502 });503 describe('when the local branch is named differently from the remote branch it\'s tracking', function() {504 let repository, wrapper;505 beforeEach(async function() {506 const {localRepoPath} = await setUpLocalAndRemoteRepositories();507 repository = await buildRepository(localRepoPath);508 wrapper = await mountAndLoad(buildApp({repository}));509 await repository.git.exec(['checkout', '-b', 'another-name', '--track', 'origin/master']);510 repository.refresh();511 });512 it('fetches with no git error', async function() {513 sinon.spy(repository, 'fetch');514 await wrapper515 .instance()516 .fetch(await wrapper.instance().fetchData(repository))();517 assert.isTrue(repository.fetch.calledWith('refs/heads/master', {518 remoteName: 'origin',519 }));520 });521 it('pulls from the correct branch', async function() {522 const prePullSHA = await repository.git.exec(['rev-parse', 'HEAD']);523 await repository.git.exec(['reset', '--hard', 'HEAD~2']);524 sinon.spy(repository, 'pull');525 await wrapper526 .instance()527 .pull(await wrapper.instance().fetchData(repository))();528 const postPullSHA = await repository.git.exec(['rev-parse', 'HEAD']);529 assert.isTrue(repository.pull.calledWith('another-name', {530 refSpec: 'master:another-name',531 }));532 assert.equal(prePullSHA, postPullSHA);533 });534 it('pushes to the correct branch', async function() {535 await repository.git.commit('new local commit', {allowEmpty: true});536 const localSHA = await repository.git.exec(['rev-parse', 'another-name']);537 sinon.spy(repository, 'push');538 await wrapper539 .instance()540 .push(await wrapper.instance().fetchData(repository))();541 const remoteSHA = await repository.git.exec(['rev-parse', 'origin/master']);542 assert.isTrue(repository.push.calledWith('another-name',543 sinon.match({refSpec: 'another-name:master'}),544 ));545 assert.equal(localSHA, remoteSHA);546 });547 });548 describe('github tile', function() {549 it('toggles the github panel when clicked', async function() {550 const workdirPath = await cloneRepository('three-files');551 const repository = await buildRepository(workdirPath);552 const toggleGithubTab = sinon.spy();553 const wrapper = await mountAndLoad(buildApp({repository, toggleGithubTab}));554 wrapper.find(GithubTileView).simulate('click');555 assert(toggleGithubTab.calledOnce);556 });557 });558 describe('changed files', function() {559 it('toggles the git panel when clicked', async function() {560 const workdirPath = await cloneRepository('three-files');561 const repository = await buildRepository(workdirPath);562 const toggleGitTab = sinon.spy();563 const wrapper = await mountAndLoad(buildApp({repository, toggleGitTab}));564 wrapper.find(ChangedFilesCountView).simulate('click');565 assert(toggleGitTab.calledOnce);566 });567 });568 describe('while the repository is not present', function() {569 it('does not display the branch or push-pull tiles', async function() {570 const workdirPath = await getTempDir();571 const repository = new Repository(workdirPath);572 assert.isFalse(repository.isPresent());573 const wrapper = await mountAndLoad(buildApp({repository}));574 assert.isFalse(wrapper.find('BranchView').exists());575 assert.isFalse(wrapper.find('BranchMenuView').exists());576 assert.isFalse(wrapper.find('PushPullView').exists());577 assert.isTrue(wrapper.find('ChangedFilesCountView').exists());578 });579 });...
model.ts
Source:model.ts
1/*---------------------------------------------------------------------------------------------2 * Copyright (c) Microsoft Corporation. All rights reserved.3 * Licensed under the MIT License. See License.txt in the project root for license information.4 *--------------------------------------------------------------------------------------------*/5import { workspace, WorkspaceFoldersChangeEvent, Uri, window, Event, EventEmitter, QuickPickItem, Disposable, SourceControl, SourceControlResourceGroup, TextEditor, Memento, OutputChannel, commands } from 'vscode';6import { Repository, RepositoryState } from './repository';7import { memoize, sequentialize, debounce } from './decorators';8import { dispose, anyEvent, filterEvent, isDescendant, pathEquals, toDisposable, eventToPromise } from './util';9import { Git } from './git';10import * as path from 'path';11import * as fs from 'fs';12import * as nls from 'vscode-nls';13import { fromGitUri } from './uri';14import { APIState as State, RemoteSourceProvider, CredentialsProvider, PushErrorHandler, PublishEvent } from './api/git';15import { Askpass } from './askpass';16import { IRemoteSourceProviderRegistry } from './remoteProvider';17import { IPushErrorHandlerRegistry } from './pushError';18import { ApiRepository } from './api/api1';19const localize = nls.loadMessageBundle();20class RepositoryPick implements QuickPickItem {21 @memoize get label(): string {22 return path.basename(this.repository.root);23 }24 @memoize get description(): string {25 return [this.repository.headLabel, this.repository.syncLabel]26 .filter(l => !!l)27 .join(' ');28 }29 constructor(public readonly repository: Repository, public readonly index: number) { }30}31export interface ModelChangeEvent {32 repository: Repository;33 uri: Uri;34}35export interface OriginalResourceChangeEvent {36 repository: Repository;37 uri: Uri;38}39interface OpenRepository extends Disposable {40 repository: Repository;41}42export class Model implements IRemoteSourceProviderRegistry, IPushErrorHandlerRegistry {43 private _onDidOpenRepository = new EventEmitter<Repository>();44 readonly onDidOpenRepository: Event<Repository> = this._onDidOpenRepository.event;45 private _onDidCloseRepository = new EventEmitter<Repository>();46 readonly onDidCloseRepository: Event<Repository> = this._onDidCloseRepository.event;47 private _onDidChangeRepository = new EventEmitter<ModelChangeEvent>();48 readonly onDidChangeRepository: Event<ModelChangeEvent> = this._onDidChangeRepository.event;49 private _onDidChangeOriginalResource = new EventEmitter<OriginalResourceChangeEvent>();50 readonly onDidChangeOriginalResource: Event<OriginalResourceChangeEvent> = this._onDidChangeOriginalResource.event;51 private openRepositories: OpenRepository[] = [];52 get repositories(): Repository[] { return this.openRepositories.map(r => r.repository); }53 private possibleGitRepositoryPaths = new Set<string>();54 private _onDidChangeState = new EventEmitter<State>();55 readonly onDidChangeState = this._onDidChangeState.event;56 private _onDidPublish = new EventEmitter<PublishEvent>();57 readonly onDidPublish = this._onDidPublish.event;58 firePublishEvent(repository: Repository, branch?: string) {59 this._onDidPublish.fire({ repository: new ApiRepository(repository), branch: branch });60 }61 private _state: State = 'uninitialized';62 get state(): State { return this._state; }63 setState(state: State): void {64 this._state = state;65 this._onDidChangeState.fire(state);66 commands.executeCommand('setContext', 'git.state', state);67 }68 @memoize69 get isInitialized(): Promise<void> {70 if (this._state === 'initialized') {71 return Promise.resolve();72 }73 return eventToPromise(filterEvent(this.onDidChangeState, s => s === 'initialized')) as Promise<any>;74 }75 private remoteSourceProviders = new Set<RemoteSourceProvider>();76 private _onDidAddRemoteSourceProvider = new EventEmitter<RemoteSourceProvider>();77 readonly onDidAddRemoteSourceProvider = this._onDidAddRemoteSourceProvider.event;78 private _onDidRemoveRemoteSourceProvider = new EventEmitter<RemoteSourceProvider>();79 readonly onDidRemoveRemoteSourceProvider = this._onDidRemoveRemoteSourceProvider.event;80 private pushErrorHandlers = new Set<PushErrorHandler>();81 private disposables: Disposable[] = [];82 constructor(readonly git: Git, private readonly askpass: Askpass, private globalState: Memento, private outputChannel: OutputChannel) {83 workspace.onDidChangeWorkspaceFolders(this.onDidChangeWorkspaceFolders, this, this.disposables);84 window.onDidChangeVisibleTextEditors(this.onDidChangeVisibleTextEditors, this, this.disposables);85 workspace.onDidChangeConfiguration(this.onDidChangeConfiguration, this, this.disposables);86 const fsWatcher = workspace.createFileSystemWatcher('**');87 this.disposables.push(fsWatcher);88 const onWorkspaceChange = anyEvent(fsWatcher.onDidChange, fsWatcher.onDidCreate, fsWatcher.onDidDelete);89 const onGitRepositoryChange = filterEvent(onWorkspaceChange, uri => /\/\.git/.test(uri.path));90 const onPossibleGitRepositoryChange = filterEvent(onGitRepositoryChange, uri => !this.getRepository(uri));91 onPossibleGitRepositoryChange(this.onPossibleGitRepositoryChange, this, this.disposables);92 this.setState('uninitialized');93 this.doInitialScan().finally(() => this.setState('initialized'));94 }95 private async doInitialScan(): Promise<void> {96 await Promise.all([97 this.onDidChangeWorkspaceFolders({ added: workspace.workspaceFolders || [], removed: [] }),98 this.onDidChangeVisibleTextEditors(window.visibleTextEditors),99 this.scanWorkspaceFolders()100 ]);101 }102 /**103 * Scans the first level of each workspace folder, looking104 * for git repositories.105 */106 private async scanWorkspaceFolders(): Promise<void> {107 const config = workspace.getConfiguration('git');108 const autoRepositoryDetection = config.get<boolean | 'subFolders' | 'openEditors'>('autoRepositoryDetection');109 if (autoRepositoryDetection !== true && autoRepositoryDetection !== 'subFolders') {110 return;111 }112 await Promise.all((workspace.workspaceFolders || []).map(async folder => {113 const root = folder.uri.fsPath;114 const children = await new Promise<string[]>((c, e) => fs.readdir(root, (err, r) => err ? e(err) : c(r)));115 const promises = children116 .filter(child => child !== '.git')117 .map(child => this.openRepository(path.join(root, child)));118 const folderConfig = workspace.getConfiguration('git', folder.uri);119 const paths = folderConfig.get<string[]>('scanRepositories') || [];120 for (const possibleRepositoryPath of paths) {121 if (path.isAbsolute(possibleRepositoryPath)) {122 console.warn(localize('not supported', "Absolute paths not supported in 'git.scanRepositories' setting."));123 continue;124 }125 promises.push(this.openRepository(path.join(root, possibleRepositoryPath)));126 }127 await Promise.all(promises);128 }));129 }130 private onPossibleGitRepositoryChange(uri: Uri): void {131 const config = workspace.getConfiguration('git');132 const autoRepositoryDetection = config.get<boolean | 'subFolders' | 'openEditors'>('autoRepositoryDetection');133 if (autoRepositoryDetection === false) {134 return;135 }136 this.eventuallyScanPossibleGitRepository(uri.fsPath.replace(/\.git.*$/, ''));137 }138 private eventuallyScanPossibleGitRepository(path: string) {139 this.possibleGitRepositoryPaths.add(path);140 this.eventuallyScanPossibleGitRepositories();141 }142 @debounce(500)143 private eventuallyScanPossibleGitRepositories(): void {144 for (const path of this.possibleGitRepositoryPaths) {145 this.openRepository(path);146 }147 this.possibleGitRepositoryPaths.clear();148 }149 private async onDidChangeWorkspaceFolders({ added, removed }: WorkspaceFoldersChangeEvent): Promise<void> {150 const possibleRepositoryFolders = added151 .filter(folder => !this.getOpenRepository(folder.uri));152 const activeRepositoriesList = window.visibleTextEditors153 .map(editor => this.getRepository(editor.document.uri))154 .filter(repository => !!repository) as Repository[];155 const activeRepositories = new Set<Repository>(activeRepositoriesList);156 const openRepositoriesToDispose = removed157 .map(folder => this.getOpenRepository(folder.uri))158 .filter(r => !!r)159 .filter(r => !activeRepositories.has(r!.repository))160 .filter(r => !(workspace.workspaceFolders || []).some(f => isDescendant(f.uri.fsPath, r!.repository.root))) as OpenRepository[];161 openRepositoriesToDispose.forEach(r => r.dispose());162 await Promise.all(possibleRepositoryFolders.map(p => this.openRepository(p.uri.fsPath)));163 }164 private onDidChangeConfiguration(): void {165 const possibleRepositoryFolders = (workspace.workspaceFolders || [])166 .filter(folder => workspace.getConfiguration('git', folder.uri).get<boolean>('enabled') === true)167 .filter(folder => !this.getOpenRepository(folder.uri));168 const openRepositoriesToDispose = this.openRepositories169 .map(repository => ({ repository, root: Uri.file(repository.repository.root) }))170 .filter(({ root }) => workspace.getConfiguration('git', root).get<boolean>('enabled') !== true)171 .map(({ repository }) => repository);172 possibleRepositoryFolders.forEach(p => this.openRepository(p.uri.fsPath));173 openRepositoriesToDispose.forEach(r => r.dispose());174 }175 private async onDidChangeVisibleTextEditors(editors: readonly TextEditor[]): Promise<void> {176 const config = workspace.getConfiguration('git');177 const autoRepositoryDetection = config.get<boolean | 'subFolders' | 'openEditors'>('autoRepositoryDetection');178 if (autoRepositoryDetection !== true && autoRepositoryDetection !== 'openEditors') {179 return;180 }181 await Promise.all(editors.map(async editor => {182 const uri = editor.document.uri;183 if (uri.scheme !== 'file') {184 return;185 }186 const repository = this.getRepository(uri);187 if (repository) {188 return;189 }190 await this.openRepository(path.dirname(uri.fsPath));191 }));192 }193 @sequentialize194 async openRepository(path: string): Promise<void> {195 if (this.getRepository(path)) {196 return;197 }198 const config = workspace.getConfiguration('git', Uri.file(path));199 const enabled = config.get<boolean>('enabled') === true;200 if (!enabled) {201 return;202 }203 try {204 const rawRoot = await this.git.getRepositoryRoot(path);205 // This can happen whenever `path` has the wrong case sensitivity in206 // case insensitive file systems207 // https://github.com/microsoft/vscode/issues/33498208 const repositoryRoot = Uri.file(rawRoot).fsPath;209 if (this.getRepository(repositoryRoot)) {210 return;211 }212 if (this.shouldRepositoryBeIgnored(rawRoot)) {213 return;214 }215 const dotGit = await this.git.getRepositoryDotGit(repositoryRoot);216 const repository = new Repository(this.git.open(repositoryRoot, dotGit), this, this, this.globalState, this.outputChannel);217 this.open(repository);218 await repository.status();219 } catch (ex) {220 // noop221 this.outputChannel.appendLine(`Opening repository for path='${path}' failed; ex=${ex}`);222 }223 }224 private shouldRepositoryBeIgnored(repositoryRoot: string): boolean {225 const config = workspace.getConfiguration('git');226 const ignoredRepos = config.get<string[]>('ignoredRepositories') || [];227 for (const ignoredRepo of ignoredRepos) {228 if (path.isAbsolute(ignoredRepo)) {229 if (pathEquals(ignoredRepo, repositoryRoot)) {230 return true;231 }232 } else {233 for (const folder of workspace.workspaceFolders || []) {234 if (pathEquals(path.join(folder.uri.fsPath, ignoredRepo), repositoryRoot)) {235 return true;236 }237 }238 }239 }240 return false;241 }242 private open(repository: Repository): void {243 this.outputChannel.appendLine(`Open repository: ${repository.root}`);244 const onDidDisappearRepository = filterEvent(repository.onDidChangeState, state => state === RepositoryState.Disposed);245 const disappearListener = onDidDisappearRepository(() => dispose());246 const changeListener = repository.onDidChangeRepository(uri => this._onDidChangeRepository.fire({ repository, uri }));247 const originalResourceChangeListener = repository.onDidChangeOriginalResource(uri => this._onDidChangeOriginalResource.fire({ repository, uri }));248 const shouldDetectSubmodules = workspace249 .getConfiguration('git', Uri.file(repository.root))250 .get<boolean>('detectSubmodules') as boolean;251 const submodulesLimit = workspace252 .getConfiguration('git', Uri.file(repository.root))253 .get<number>('detectSubmodulesLimit') as number;254 const checkForSubmodules = () => {255 if (!shouldDetectSubmodules) {256 return;257 }258 if (repository.submodules.length > submodulesLimit) {259 window.showWarningMessage(localize('too many submodules', "The '{0}' repository has {1} submodules which won't be opened automatically. You can still open each one individually by opening a file within.", path.basename(repository.root), repository.submodules.length));260 statusListener.dispose();261 }262 repository.submodules263 .slice(0, submodulesLimit)264 .map(r => path.join(repository.root, r.path))265 .forEach(p => this.eventuallyScanPossibleGitRepository(p));266 };267 const statusListener = repository.onDidRunGitStatus(checkForSubmodules);268 checkForSubmodules();269 const dispose = () => {270 disappearListener.dispose();271 changeListener.dispose();272 originalResourceChangeListener.dispose();273 statusListener.dispose();274 repository.dispose();275 this.openRepositories = this.openRepositories.filter(e => e !== openRepository);276 this._onDidCloseRepository.fire(repository);277 };278 const openRepository = { repository, dispose };279 this.openRepositories.push(openRepository);280 this._onDidOpenRepository.fire(repository);281 }282 close(repository: Repository): void {283 const openRepository = this.getOpenRepository(repository);284 if (!openRepository) {285 return;286 }287 this.outputChannel.appendLine(`Close repository: ${repository.root}`);288 openRepository.dispose();289 }290 async pickRepository(): Promise<Repository | undefined> {291 if (this.openRepositories.length === 0) {292 throw new Error(localize('no repositories', "There are no available repositories"));293 }294 const picks = this.openRepositories.map((e, index) => new RepositoryPick(e.repository, index));295 const active = window.activeTextEditor;296 const repository = active && this.getRepository(active.document.fileName);297 const index = picks.findIndex(pick => pick.repository === repository);298 // Move repository pick containing the active text editor to appear first299 if (index > -1) {300 picks.unshift(...picks.splice(index, 1));301 }302 const placeHolder = localize('pick repo', "Choose a repository");303 const pick = await window.showQuickPick(picks, { placeHolder });304 return pick && pick.repository;305 }306 getRepository(sourceControl: SourceControl): Repository | undefined;307 getRepository(resourceGroup: SourceControlResourceGroup): Repository | undefined;308 getRepository(path: string): Repository | undefined;309 getRepository(resource: Uri): Repository | undefined;310 getRepository(hint: any): Repository | undefined {311 const liveRepository = this.getOpenRepository(hint);312 return liveRepository && liveRepository.repository;313 }314 private getOpenRepository(repository: Repository): OpenRepository | undefined;315 private getOpenRepository(sourceControl: SourceControl): OpenRepository | undefined;316 private getOpenRepository(resourceGroup: SourceControlResourceGroup): OpenRepository | undefined;317 private getOpenRepository(path: string): OpenRepository | undefined;318 private getOpenRepository(resource: Uri): OpenRepository | undefined;319 private getOpenRepository(hint: any): OpenRepository | undefined {320 if (!hint) {321 return undefined;322 }323 if (hint instanceof Repository) {324 return this.openRepositories.filter(r => r.repository === hint)[0];325 }326 if (typeof hint === 'string') {327 hint = Uri.file(hint);328 }329 if (hint instanceof Uri) {330 let resourcePath: string;331 if (hint.scheme === 'git') {332 resourcePath = fromGitUri(hint).path;333 } else {334 resourcePath = hint.fsPath;335 }336 outer:337 for (const liveRepository of this.openRepositories.sort((a, b) => b.repository.root.length - a.repository.root.length)) {338 if (!isDescendant(liveRepository.repository.root, resourcePath)) {339 continue;340 }341 for (const submodule of liveRepository.repository.submodules) {342 const submoduleRoot = path.join(liveRepository.repository.root, submodule.path);343 if (isDescendant(submoduleRoot, resourcePath)) {344 continue outer;345 }346 }347 return liveRepository;348 }349 return undefined;350 }351 for (const liveRepository of this.openRepositories) {352 const repository = liveRepository.repository;353 if (hint === repository.sourceControl) {354 return liveRepository;355 }356 if (hint === repository.mergeGroup || hint === repository.indexGroup || hint === repository.workingTreeGroup) {357 return liveRepository;358 }359 }360 return undefined;361 }362 getRepositoryForSubmodule(submoduleUri: Uri): Repository | undefined {363 for (const repository of this.repositories) {364 for (const submodule of repository.submodules) {365 const submodulePath = path.join(repository.root, submodule.path);366 if (submodulePath === submoduleUri.fsPath) {367 return repository;368 }369 }370 }371 return undefined;372 }373 registerRemoteSourceProvider(provider: RemoteSourceProvider): Disposable {374 this.remoteSourceProviders.add(provider);375 this._onDidAddRemoteSourceProvider.fire(provider);376 return toDisposable(() => {377 this.remoteSourceProviders.delete(provider);378 this._onDidRemoveRemoteSourceProvider.fire(provider);379 });380 }381 registerCredentialsProvider(provider: CredentialsProvider): Disposable {382 return this.askpass.registerCredentialsProvider(provider);383 }384 getRemoteProviders(): RemoteSourceProvider[] {385 return [...this.remoteSourceProviders.values()];386 }387 registerPushErrorHandler(handler: PushErrorHandler): Disposable {388 this.pushErrorHandlers.add(handler);389 return toDisposable(() => this.pushErrorHandlers.delete(handler));390 }391 getPushErrorHandlers(): PushErrorHandler[] {392 return [...this.pushErrorHandlers];393 }394 dispose(): void {395 const openRepositories = [...this.openRepositories];396 openRepositories.forEach(r => r.dispose());397 this.openRepositories = [];398 this.possibleGitRepositoryPaths.clear();399 this.disposables = dispose(this.disposables);400 }...
index.ts
Source:index.ts
1import { container } from 'tsyringe';2import '@modules/accesses/providers';3import './providers';4import IAccessTokensRepository from '@modules/accesses/repositories/IAccessTokensRepository';5import AccessTokensRepository from '@modules/accesses/infra/typeorm/repositories/AccessTokensRepository';6import IAccessesRepository from '@modules/accesses/repositories/IAccessesRepository';7import AccessesRepository from '@modules/accesses/infra/typeorm/repositories/AccessesRepository';8import ISectorsRepository from '@modules/sectors/repositories/ISectorsRepository';9import SectorsRepository from '@modules/sectors/infra/typeorm/repositories/SectorsRepository';10import IGoalsRepository from '@modules/goals/repositories/IGoalsRepository';11import GoalsRepository from '@modules/goals/infra/typeorm/repositories/GoalsRepository';12import ISubGoalsRepository from '@modules/sub_goals/repositories/ISubGoalsRepository';13import SubGoalsRepository from '@modules/sub_goals/infra/typeorm/repositories/SubGoalsRepository';14import ISubGoalsOfGoalsRepository from '@modules/sub_goals_of_goals/repositories/ISubGoalsOfGoalsRepository';15import SubGoalsOfGoalsRepository from '@modules/sub_goals_of_goals/infra/typeorm/repositories/SubGoalsOfGoalsRepository';16import IGoalsOfSectorsRepository from '@modules/goals_of_sectors/repositories/IGoalsOfSectorsRepository';17import GoalsOfSectorsRepository from '@modules/goals_of_sectors/infra/typeorm/repositories/GoalsOfSectorsRepository';18import IEmployeesRepository from '@modules/employees/repositories/IEmployeesRepository';19import EmployeesRepository from '@modules/employees/infra/typeorm/repositories/EmployeesRepository';20import IAnalysisModuleRepository from '@modules/analysis_module/repositories/IAnalysisModuleRepository';21import AnalysisModuleRepository from '@modules/analysis_module/infra/typeorm/repositories/AnalysisModuleRepository';22import IAnalysisModuleOfGoalsRepository from '@modules/analysis_module_of_goals/repositories/IAnalysisModuleOfGoalsRepository';23import AnalysisModuleOfGoalsRepository from '@modules/analysis_module_of_goals/infra/typeorm/repositories/AnalysisModuleOfGoalsRepository';24import IResultsOfSubGoalsRepository from '@modules/results_of_sub_goals/repositories/IResultsOfSubGoalsRepository';25import ResultsOfSubGoalsRepository from '@modules/results_of_sub_goals/infra/typeorm/repositories/ResultsOfSubGoalsRepository';26import ITasksRepository from '@modules/tasks/repositories/ITasksRepository';27import TasksRepository from '@modules/tasks/infra/typeorm/repositories/TasksRepository';28import ITasksOfSubGoalsRepository from '@modules/tasks_of_sub_goals/repositories/ITasksOfSubGoalsRepository';29import TasksOfSubGoalsRepository from '@modules/tasks_of_sub_goals/infra/typeorm/repositories/TasksOfSubGoalsRepository';30container.registerSingleton<IAccessesRepository>(31 'AccessesRepository',32 AccessesRepository,33);34container.registerSingleton<IAccessTokensRepository>(35 'AccessTokensRepository',36 AccessTokensRepository,37);38container.registerSingleton<ISectorsRepository>(39 'SectorsRepository',40 SectorsRepository,41);42container.registerSingleton<IGoalsRepository>(43 'GoalsRepository',44 GoalsRepository,45);46container.registerSingleton<ISubGoalsRepository>(47 'SubGoalsRepository',48 SubGoalsRepository,49);50container.registerSingleton<ISubGoalsOfGoalsRepository>(51 'SubGoalsOfGoalsRepository',52 SubGoalsOfGoalsRepository,53);54container.registerSingleton<IGoalsOfSectorsRepository>(55 'GoalsOfSectorsRepository',56 GoalsOfSectorsRepository,57);58container.registerSingleton<IEmployeesRepository>(59 'EmployeesRepository',60 EmployeesRepository,61);62container.registerSingleton<IAnalysisModuleRepository>(63 'AnalysisModuleRepository',64 AnalysisModuleRepository,65);66container.registerSingleton<IAnalysisModuleOfGoalsRepository>(67 'AnalysisModuleOfGoalsRepository',68 AnalysisModuleOfGoalsRepository,69);70container.registerSingleton<IResultsOfSubGoalsRepository>(71 'ResultsOfSubGoalsRepository',72 ResultsOfSubGoalsRepository,73);74container.registerSingleton<ITasksRepository>(75 'TasksRepository',76 TasksRepository,77);78container.registerSingleton<ITasksOfSubGoalsRepository>(79 'TasksOfSubGoalsRepository',80 TasksOfSubGoalsRepository,...
GetWorldService.ts
Source:GetWorldService.ts
1import {World} from '../../domain/World';2import {IPlayerRepository} from '../../repos/IPlayerRepository';3import {ICityRepository} from '../../repos/ICityRepository';4import {IMapRepository} from '../../repos/IMapRepository';5import {WorldFactory} from '../../factories/WorldFactory';6import {ITileRepository} from '../../repos/ITileRepository';7import {EntityID} from '../../../../shared/domain/EntityID';8import {IMarchRepository} from '../../repos/IMarchRepository';9/**10 * Service for handling get world11 *12 * @export13 * @class GetWorldService14 */15export class GetWorldService {16 // private worldRepository: IWorldRepository;17 private playerRepository: IPlayerRepository;18 private cityRepository: ICityRepository;19 private mapRepository: IMapRepository;20 private marchRepository: IMarchRepository;21 private tileRepository: ITileRepository;22 private worldFactory: WorldFactory;23 /**24 * Creates an instance of GetWorldService.25 *26 * @param {IPlayerRepository} playerRepository27 * @param {ICityRepository} cityRepository28 * @param {IMapRepository} mapRepository29 * @param {IMarchRepository} marchRepository30 * @param {ITileRepository} tileRepository31 * @memberof GetWorldService32 */33 constructor(34 playerRepository: IPlayerRepository,35 cityRepository: ICityRepository,36 mapRepository: IMapRepository,37 marchRepository: IMarchRepository,38 tileRepository: ITileRepository,39 ) {40 this.playerRepository = playerRepository;41 this.cityRepository = cityRepository;42 this.marchRepository = marchRepository;43 this.mapRepository = mapRepository;44 this.tileRepository = tileRepository;45 this.worldFactory = new WorldFactory();46 }47 /**48 * Returns a domain entity for this world.49 *50 * @return {Promise<World>}51 * @memberof GetWorldService52 */53 async getWorld(): Promise<World> {54 // get all the players in the world55 const players = await this.playerRepository.getAllPlayers();56 // get the world's map & all its tiles57 const map = await this.mapRepository.getMap();58 map.$tiles = await this.tileRepository.getAllTiles(map);59 // get all the cities in the world60 const cities = await this.cityRepository.getAllCities();61 // get all the marches in the world62 const marches = await this.marchRepository.getAllMarches();63 // return the world entity64 return this.worldFactory.createWorld(65 new EntityID(1),66 players,67 map,68 cities,69 marches,70 );71 }...
index.js
Source:index.js
1"use strict";2var _tsyringe = require("tsyringe");3require("@shared/container/providers");4var _UsersRepository = require("@modules/accounts/infra/typeorm/repositories/UsersRepository");5var _CategoriesRepository = require("@modules/cars/infra/typeorm/repositories/CategoriesRepository");6var _SpecificationsRepository = require("@modules/cars/infra/typeorm/repositories/SpecificationsRepository");7var _CarsRepository = require("@modules/cars/infra/typeorm/repositories/CarsRepository");8var _CarsImagesRepository = require("@modules/cars/infra/typeorm/repositories/CarsImagesRepository");9var _RentalsRepository = require("@modules/rentals/infra/typeorm/repositories/RentalsRepository");10var _UsersTokensRepository = require("@modules/accounts/infra/typeorm/repositories/UsersTokensRepository");11_tsyringe.container.registerSingleton("CategoriesRepository", _CategoriesRepository.CategoriesRepository);12_tsyringe.container.registerSingleton("SpecificationsRepository", _SpecificationsRepository.SpecificationsRepository);13_tsyringe.container.registerSingleton("UsersRepository", _UsersRepository.UsersRepository);14_tsyringe.container.registerSingleton("CarsRepository", _CarsRepository.CarsRepository);15_tsyringe.container.registerSingleton("CarsImagesRepository", _CarsImagesRepository.CarsImagesRepository);16_tsyringe.container.registerSingleton("RentalsRepository", _RentalsRepository.RentalsRepository);...
Using AI Code Generation
1const { launch } = require('qawolf');2const selectors = require('../selectors/test.json');3describe('test', () => {4 let browser;5 beforeAll(async () => {6 browser = await launch();7 });8 afterAll(async () => {9 await browser.close();10 });11 it('test', async () => {12 const page = await browser.newPage();13 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)']);14 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)']);15 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)']);16 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)']);17 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)']);18 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)']);19 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)']);20 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)']);21 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)']);22 await page.click(selectors['#tsf > div:nth-child
Using AI Code Generation
1const { launch } = require('qawolf');2const selectors = require('./selectors/test.json');3describe('test', () => {4 let browser;5 let page;6 beforeAll(async () => {7 browser = await launch();8 });9 afterAll(async () => {10 await browser.close();11 });12 beforeEach(async () => {13 page = await browser.newPage();14 });15 afterEach(async () => {16 await page.close();17 });18 it('test', async () => {19 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)']);20 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)']);21 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)']);22 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)']);23 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)']);24 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)']);25 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)']);26 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type="submit"]:nth-child(1)']);27 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input
Using AI Code Generation
1const { launch } = require("qawolf");2const selectors = require("./selectors/test.json");3describe("test", () => {4 let browser;5 beforeAll(async () => {6 browser = await launch();7 });8 afterAll(async () => {9 await browser.close();10 });11 it("test", async () => {12 const page = await browser.newPage();13 await page.click(selectors["Search"]);14 await page.fill(selectors["Search"], "Hello World");15 await page.press(selectors["Search"], "Enter");16 await page.screenshot({ path: `test.png` });17 });18});19{20}
Using AI Code Generation
1const { launch } = require("qawolf");2const selectors = require("../qawolf/selectors/test");3describe("test", () => {4 let browser;5 let page;6 beforeAll(async () => {7 browser = await launch();8 page = await browser.newPage();9 });10 afterAll(async () => {11 await browser.close();12 });13 it("test", async () => {14 await page.click(selectors["Search Google or type a URL"]);15 await page.fill(selectors["Search Google or type a URL"], "qawolf");16 await page.press(selectors["Search Google or type a URL"], "Enter");17 });18});19module.exports = {20 "Search Google or type a URL": "#tsf > div:nth-child(2) > div > div.RNNXgb > div > div.a4bIc > input",21};22{23 "scripts": {24 },25 "devDependencies": {26 }27}28module.exports = {29 ['jest-html-reporters', {30 }]31};32module.exports = {33 launchOptions: {34 },35 contextOptions: {36 },37 serverOptions: {38 },39};
Using AI Code Generation
1const { launch, test } = require("qawolf");2const selectors = require("../selectors/test");3test("test", async (browser) => {4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click(selectors["input[name='q']"]);7 await page.fill(selectors["input[name='q']"], "qawolf");8 await page.keyboard.press("Enter");9});10module.exports = {11};
Using AI Code Generation
1const { create } = require("qawolf");2exports.handler = async (event, context) => {3 const browser = await create();4 const page = await browser.newPage();5 await page.type("#tsf > div:nth-child(2) > div > div.RNNXgb > div > div.a4bIc > input", "qawolf");6 await page.click("#tsf > div:nth-child(2) > div > div.FPdoLc.VlcLAe > center > input[type=\"submit\"]:nth-child(1)");7 await page.click("#rso > div:nth-child(1) > div > div:nth-child(1) > div > div > div.r > a > h3");8 await page.click("#__next > div > div > div > div > div > div > div > div > div > div > div > div > div > div > div:nth-child(1) > div > div > a");9 await page.click("#__next > div > div > div > div > div > div > div > div > div > div > div > div > div > div > div:nth-child(1) > div > div > a");10 await page.click("#__next > div > div > div > div > div > div > div > div > div > div > div > div > div > div > div:nth-child(1) > div > div > a");11 await page.click("#__next > div > div > div > div > div > div > div > div > div > div > div > div > div > div > div:nth-child(1) > div > div > a");12 await page.click("#__next > div > div > div > div > div > div > div > div > div > div > div > div > div > div > div:nth-child(1) > div > div > a");13 await page.click("#__next > div > div > div > div > div > div > div > div > div > div > div > div > div > div > div:nth-child(1) > div > div > a");14 await page.click("#__next > div > div > div > div > div > div > div > div > div > div > div > div > div > div > div:nth-child(
Using AI Code Generation
1import { launch, Page, test } from 'qawolf';2import selectors from './selectors/test.json';3test.describe('test', () => {4 let page: Page;5 test.beforeAll(async () => {6 });7 test.afterAll(async () => {8 await page.close();9 });10 test('test', async () => {11 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.tfB0Bf > center > input[type="submit"]:nth-child(1)']);12 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.tfB0Bf > center > input[type="submit"]:nth-child(1)']);13 await page.click(selectors['#tsf > div:nth-child(2) > div > div.FPdoLc.tfB0Bf > center > input[type="submit"]:nth-child(1)']);14 });15});16await page.type(selectors['#ts
Using AI Code Generation
1const { create } = require("qawolf");2const opts = {3 launchOptions: {4 },5};6async function test() {7 const browser = await create(opts);8 const page = await browser.newPage();9 await page.click("input[name=q]");10 await page.type("input[name=q]", "Hello World");11 await page.click("input[name=q]");12 await page.keyboard.press("Enter");13 await page.waitForSelector(".g");14 await browser.close();15}16test();17{18 "scripts": {19 },20 "dependencies": {21 }22}
Using AI Code Generation
1const qawolf = require("qawolf");2const { launch, openBrowser, goto, text, write, closeBrowser } = require('taiko');3(async () => {4 try {5 await launch();6 const browser = await openBrowser();7 await write("qawolf");8 await press("Enter");9 await text("qawolf").exists();10 await qawolf.create();11 await closeBrowser();12 } catch (error) {13 console.error(error);14 } finally {15 await closeBrowser();16 }17})();18{19 {20 },21 {22 }23}24const qawolf = require("qawolf");25const { openBrowser, goto, text, write, closeBrowser } = require('taiko');26(async () => {27 try {28 const browser = await openBrowser();29 await write("qawolf");30 await press("Enter");31 await text("qawolf").exists();32 await qawolf.create();33 await closeBrowser();34 } catch (error) {35 console.error(error);36 } finally {37 await closeBrowser();38 }39})();
Using AI Code Generation
1const { launch, login } = require("../qawolf/login");2const { create, update } = require("../qawolf/create");3const { delete } = require("../qawolf/delete");4const { logout } = require("../qawolf/logout");5(async () => {6 const browser = await launch();7 const page = await browser.newPage();8 await login(page);9 await create(page);10 await update(page);11 await delete(page);12 await logout(page);13 await browser.close();14})();15const { login } = require("../qawolf/login");16const { create } = require("../qawolf/create");17const { update } = require("../qawolf/update");18const { delete } = require("../qawolf/delete");19const { logout } = require("../qawolf/logout");20module.exports = { login, create, update, delete, logout };21const { login } = require("../qawolf/login");22const { create } = require("../qawolf/create");23const { update } = require("../qawolf/update");24const { delete } = require("../qawolf/delete");25const { logout } = require("../qawolf/logout");26module.exports = { login, create, update, delete, logout };27const { login } = require("../qawolf/login");28const { create } = require("../qawolf/create");29const { update } = require("../qawolf/update");30const { delete } = require("../qawolf/delete");31const { logout } = require("../qawolf/logout");32module.exports = { login, create, update, delete, logout };33const { login } = require("../qawolf/login");34const { create } = require("../qawolf/create");35const { update } = require("../qawolf/update");36const { delete } = require("../qawolf/delete");37const { logout } = require("../qawolf/logout");38module.exports = { login, create, update, delete, logout };39const { login } = require("../qawolf/login");40const { create } = require("../qawolf/create");41const { update } = require("../qaw
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!