integrationRepos.tsx 8.5 KB

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