integrationRepos.tsx 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import {Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import debounce from 'lodash/debounce';
  4. import {addRepository, migrateRepository} from 'sentry/actionCreators/integrations';
  5. import Alert from 'sentry/components/alert';
  6. import AsyncComponent from 'sentry/components/asyncComponent';
  7. import Button from 'sentry/components/button';
  8. import DropdownAutoComplete from 'sentry/components/dropdownAutoComplete';
  9. import DropdownButton from 'sentry/components/dropdownButton';
  10. import EmptyMessage from 'sentry/components/emptyMessage';
  11. import Pagination from 'sentry/components/pagination';
  12. import {Panel, PanelBody, PanelHeader} from 'sentry/components/panels';
  13. import RepositoryRow from 'sentry/components/repositoryRow';
  14. import {IconCommit} from 'sentry/icons';
  15. import {t} from 'sentry/locale';
  16. import RepositoryStore from 'sentry/stores/repositoryStore';
  17. import space from 'sentry/styles/space';
  18. import {Integration, Organization, Repository} from 'sentry/types';
  19. import withOrganization from 'sentry/utils/withOrganization';
  20. type Props = AsyncComponent['props'] & {
  21. integration: Integration;
  22. organization: Organization;
  23. };
  24. type State = AsyncComponent['state'] & {
  25. adding: boolean;
  26. dropdownBusy: boolean;
  27. integrationRepos: {
  28. repos: {identifier: string; name: string}[];
  29. searchable: boolean;
  30. };
  31. itemList: Repository[];
  32. };
  33. class IntegrationRepos extends AsyncComponent<Props, State> {
  34. getDefaultState(): State {
  35. return {
  36. ...super.getDefaultState(),
  37. adding: false,
  38. itemList: [],
  39. integrationRepos: {repos: [], searchable: false},
  40. dropdownBusy: false,
  41. };
  42. }
  43. getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
  44. const orgId = this.props.organization.slug;
  45. return [
  46. ['itemList', `/organizations/${orgId}/repos/`, {query: {status: ''}}],
  47. [
  48. 'integrationRepos',
  49. `/organizations/${orgId}/integrations/${this.props.integration.id}/repos/`,
  50. ],
  51. ];
  52. }
  53. getIntegrationRepos() {
  54. const integrationId = this.props.integration.id;
  55. return this.state.itemList.filter(repo => repo.integrationId === integrationId);
  56. }
  57. // Called by row to signal repository change.
  58. onRepositoryChange = data => {
  59. const itemList = this.state.itemList;
  60. itemList.forEach(item => {
  61. if (item.id === data.id) {
  62. item.status = data.status;
  63. // allow for custom scm repositories to be updated, and
  64. // url is optional and therefore can be an empty string
  65. item.url = data.url === undefined ? item.url : data.url;
  66. item.name = data.name || item.name;
  67. }
  68. });
  69. this.setState({itemList});
  70. RepositoryStore.resetRepositories();
  71. };
  72. debouncedSearchRepositoriesRequest = debounce(
  73. query => this.searchRepositoriesRequest(query),
  74. 200
  75. );
  76. searchRepositoriesRequest = (searchQuery: string) => {
  77. const orgId = this.props.organization.slug;
  78. const query = {search: searchQuery};
  79. const endpoint = `/organizations/${orgId}/integrations/${this.props.integration.id}/repos/`;
  80. return this.api.request(endpoint, {
  81. method: 'GET',
  82. query,
  83. success: data => {
  84. this.setState({integrationRepos: data, dropdownBusy: false});
  85. },
  86. error: () => {
  87. this.setState({dropdownBusy: false});
  88. },
  89. });
  90. };
  91. handleSearchRepositories = (e: React.ChangeEvent<HTMLInputElement>) => {
  92. this.setState({dropdownBusy: true});
  93. this.debouncedSearchRepositoriesRequest(e.target.value);
  94. };
  95. addRepo(selection: {label: JSX.Element; searchKey: string; value: string}) {
  96. const {integration} = this.props;
  97. const {itemList} = this.state;
  98. const orgId = this.props.organization.slug;
  99. this.setState({adding: true});
  100. const migratableRepo = itemList.filter(item => {
  101. if (!(selection.value && item.externalSlug)) {
  102. return false;
  103. }
  104. return selection.value === item.externalSlug;
  105. })[0];
  106. let promise: Promise<Repository>;
  107. if (migratableRepo) {
  108. promise = migrateRepository(this.api, orgId, migratableRepo.id, integration);
  109. } else {
  110. promise = addRepository(this.api, orgId, selection.value, integration);
  111. }
  112. promise.then(
  113. (repo: Repository) => {
  114. this.setState({adding: false, itemList: itemList.concat(repo)});
  115. RepositoryStore.resetRepositories();
  116. },
  117. () => this.setState({adding: false})
  118. );
  119. }
  120. renderDropdown() {
  121. const access = new Set(this.props.organization.access);
  122. if (!access.has('org:integrations')) {
  123. return (
  124. <DropdownButton
  125. disabled
  126. title={t(
  127. 'You must be an organization owner, manager or admin to add repositories'
  128. )}
  129. isOpen={false}
  130. size="xs"
  131. >
  132. {t('Add Repository')}
  133. </DropdownButton>
  134. );
  135. }
  136. const repositories = new Set(
  137. this.state.itemList.filter(item => item.integrationId).map(i => i.externalSlug)
  138. );
  139. const repositoryOptions = (this.state.integrationRepos.repos || []).filter(
  140. repo => !repositories.has(repo.identifier)
  141. );
  142. const items = repositoryOptions.map(repo => ({
  143. searchKey: repo.name,
  144. value: repo.identifier,
  145. label: (
  146. <StyledListElement>
  147. <StyledName>{repo.name}</StyledName>
  148. </StyledListElement>
  149. ),
  150. }));
  151. const menuHeader = <StyledReposLabel>{t('Repositories')}</StyledReposLabel>;
  152. const onChange = this.state.integrationRepos.searchable
  153. ? this.handleSearchRepositories
  154. : undefined;
  155. return (
  156. <DropdownAutoComplete
  157. items={items}
  158. onSelect={this.addRepo.bind(this)}
  159. onChange={onChange}
  160. menuHeader={menuHeader}
  161. emptyMessage={t('No repositories available')}
  162. noResultsMessage={t('No repositories found')}
  163. busy={this.state.dropdownBusy}
  164. alignMenu="right"
  165. >
  166. {({isOpen}) => (
  167. <DropdownButton isOpen={isOpen} size="xs" busy={this.state.adding}>
  168. {t('Add Repository')}
  169. </DropdownButton>
  170. )}
  171. </DropdownAutoComplete>
  172. );
  173. }
  174. renderError(error) {
  175. const badRequest = Object.values(this.state.errors).find(
  176. resp => resp && resp.status === 400
  177. );
  178. if (badRequest) {
  179. return (
  180. <Alert type="error" showIcon>
  181. {t(
  182. 'We were unable to fetch repositories for this integration. Try again later. If this error continues, please reconnect this integration by uninstalling and then reinstalling.'
  183. )}
  184. </Alert>
  185. );
  186. }
  187. return super.renderError(error);
  188. }
  189. renderBody() {
  190. const {itemListPageLinks} = this.state;
  191. const orgId = this.props.organization.slug;
  192. const itemList = this.getIntegrationRepos() || [];
  193. const header = (
  194. <PanelHeader disablePadding hasButtons>
  195. <HeaderText>{t('Repositories')}</HeaderText>
  196. <DropdownWrapper>{this.renderDropdown()}</DropdownWrapper>
  197. </PanelHeader>
  198. );
  199. return (
  200. <Fragment>
  201. <Panel>
  202. {header}
  203. <PanelBody>
  204. {itemList.length === 0 && (
  205. <EmptyMessage
  206. icon={<IconCommit />}
  207. title={t('Sentry is better with commit data')}
  208. description={t(
  209. 'Add a repository to begin tracking its commit data. Then, set up release tracking to unlock features like suspect commits, suggested issue owners, and deploy emails.'
  210. )}
  211. action={
  212. <Button href="https://docs.sentry.io/product/releases/">
  213. {t('Learn More')}
  214. </Button>
  215. }
  216. />
  217. )}
  218. {itemList.map(repo => (
  219. <RepositoryRow
  220. api={this.api}
  221. key={repo.id}
  222. repository={repo}
  223. orgId={orgId}
  224. onRepositoryChange={this.onRepositoryChange}
  225. />
  226. ))}
  227. </PanelBody>
  228. </Panel>
  229. {itemListPageLinks && (
  230. <Pagination pageLinks={itemListPageLinks} {...this.props} />
  231. )}
  232. </Fragment>
  233. );
  234. }
  235. }
  236. export default withOrganization(IntegrationRepos);
  237. const HeaderText = styled('div')`
  238. padding-left: ${space(2)};
  239. flex: 1;
  240. `;
  241. const DropdownWrapper = styled('div')`
  242. padding-right: ${space(1)};
  243. text-transform: none;
  244. `;
  245. const StyledReposLabel = styled('div')`
  246. width: 250px;
  247. font-size: 0.875em;
  248. padding: ${space(1)} 0;
  249. text-transform: uppercase;
  250. `;
  251. const StyledListElement = styled('div')`
  252. display: flex;
  253. align-items: center;
  254. padding: ${space(0.5)};
  255. `;
  256. const StyledName = styled('div')`
  257. flex-shrink: 1;
  258. min-width: 0;
  259. ${p => p.theme.overflowEllipsis};
  260. `;