integrationRepos.tsx 8.4 KB

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