integrationRepos.tsx 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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 (
  123. !['github', 'gitlab'].includes(this.props.integration.provider.key) &&
  124. !access.has('org:integrations')
  125. ) {
  126. return (
  127. <DropdownButton
  128. disabled
  129. title={t(
  130. 'You must be an organization owner, manager or admin to add repositories'
  131. )}
  132. isOpen={false}
  133. size="xs"
  134. >
  135. {t('Add Repository')}
  136. </DropdownButton>
  137. );
  138. }
  139. const repositories = new Set(
  140. this.state.itemList.filter(item => item.integrationId).map(i => i.externalSlug)
  141. );
  142. const repositoryOptions = (this.state.integrationRepos.repos || []).filter(
  143. repo => !repositories.has(repo.identifier)
  144. );
  145. const items = repositoryOptions.map(repo => ({
  146. searchKey: repo.name,
  147. value: repo.identifier,
  148. label: (
  149. <StyledListElement>
  150. <StyledName>{repo.name}</StyledName>
  151. </StyledListElement>
  152. ),
  153. }));
  154. const menuHeader = <StyledReposLabel>{t('Repositories')}</StyledReposLabel>;
  155. const onChange = this.state.integrationRepos.searchable
  156. ? this.handleSearchRepositories
  157. : undefined;
  158. return (
  159. <DropdownAutoComplete
  160. items={items}
  161. onSelect={this.addRepo.bind(this)}
  162. onChange={onChange}
  163. menuHeader={menuHeader}
  164. emptyMessage={t('No repositories available')}
  165. noResultsMessage={t('No repositories found')}
  166. busy={this.state.dropdownBusy}
  167. alignMenu="right"
  168. >
  169. {({isOpen}) => (
  170. <DropdownButton isOpen={isOpen} size="xs" busy={this.state.adding}>
  171. {t('Add Repository')}
  172. </DropdownButton>
  173. )}
  174. </DropdownAutoComplete>
  175. );
  176. }
  177. renderError(error) {
  178. const badRequest = Object.values(this.state.errors).find(
  179. resp => resp && resp.status === 400
  180. );
  181. if (badRequest) {
  182. return (
  183. <Alert type="error" showIcon>
  184. {t(
  185. '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.'
  186. )}
  187. </Alert>
  188. );
  189. }
  190. return super.renderError(error);
  191. }
  192. renderBody() {
  193. const {itemListPageLinks} = this.state;
  194. const orgId = this.props.organization.slug;
  195. const itemList = this.getIntegrationRepos() || [];
  196. const header = (
  197. <PanelHeader disablePadding hasButtons>
  198. <HeaderText>{t('Repositories')}</HeaderText>
  199. <DropdownWrapper>{this.renderDropdown()}</DropdownWrapper>
  200. </PanelHeader>
  201. );
  202. return (
  203. <Fragment>
  204. <Panel>
  205. {header}
  206. <PanelBody>
  207. {itemList.length === 0 && (
  208. <EmptyMessage
  209. icon={<IconCommit />}
  210. title={t('Sentry is better with commit data')}
  211. description={t(
  212. '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.'
  213. )}
  214. action={
  215. <Button href="https://docs.sentry.io/product/releases/">
  216. {t('Learn More')}
  217. </Button>
  218. }
  219. />
  220. )}
  221. {itemList.map(repo => (
  222. <RepositoryRow
  223. api={this.api}
  224. key={repo.id}
  225. repository={repo}
  226. orgId={orgId}
  227. onRepositoryChange={this.onRepositoryChange}
  228. />
  229. ))}
  230. </PanelBody>
  231. </Panel>
  232. {itemListPageLinks && (
  233. <Pagination pageLinks={itemListPageLinks} {...this.props} />
  234. )}
  235. </Fragment>
  236. );
  237. }
  238. }
  239. export default withOrganization(IntegrationRepos);
  240. const HeaderText = styled('div')`
  241. padding-left: ${space(2)};
  242. flex: 1;
  243. `;
  244. const DropdownWrapper = styled('div')`
  245. padding-right: ${space(1)};
  246. text-transform: none;
  247. `;
  248. const StyledReposLabel = styled('div')`
  249. width: 250px;
  250. font-size: 0.875em;
  251. padding: ${space(1)} 0;
  252. text-transform: uppercase;
  253. `;
  254. const StyledListElement = styled('div')`
  255. display: flex;
  256. align-items: center;
  257. padding: ${space(0.5)};
  258. `;
  259. const StyledName = styled('div')`
  260. flex-shrink: 1;
  261. min-width: 0;
  262. ${p => p.theme.overflowEllipsis};
  263. `;