integrationRepos.tsx 8.5 KB

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