integrationRepos.tsx 8.5 KB

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