Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add ability to edit/import gitconfig when no configmap exists #1204

Merged
merged 4 commits into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
* Red Hat, Inc. - initial API and implementation
*/

import { api } from '@eclipse-che/common';
import { api, helpers } from '@eclipse-che/common';
import * as k8s from '@kubernetes/client-node';
import * as ini from 'multi-ini';

Expand Down Expand Up @@ -41,11 +41,54 @@ export class GitConfigApiService implements IGitConfigApi {

return this.toGitConfig(response.body);
} catch (error) {
if (helpers.errors.isKubeClientError(error) && error.statusCode === 404) {
// Create gitconfig configmap if it does not exist
return this.createGitConfigMap(namespace);
}

const message = `Unable to read gitconfig in the namespace "${namespace}"`;
throw createError(error, GITCONFIG_API_ERROR_LABEL, message);
}
}

/**
* @throws
* Creates `gitconfig` ConfigMap in the given `namespace`.
*/
private async createGitConfigMap(namespace: string): Promise<api.IGitConfig> {
const configMap = new k8s.V1ConfigMap();
configMap.metadata = {
name: GITCONFIG_CONFIGMAP,
namespace,
labels: {
'controller.devfile.io/mount-to-devworkspace': 'true',
'controller.devfile.io/watch-configmap': 'true',
},
annotations: {
'controller.devfile.io/mount-as': 'subpath',
'controller.devfile.io/mount-path': '/etc/',
},
};
configMap.data = {
gitconfig: this.fromGitConfig({
gitconfig: {
user: {
name: '',
email: '',
},
},
}),
};

try {
const response = await this.coreV1API.createNamespacedConfigMap(namespace, configMap);
return this.toGitConfig(response.body);
} catch (error) {
const message = `Unable to create gitconfig in the namespace "${namespace}"`;
throw createError(error, GITCONFIG_API_ERROR_LABEL, message);
}
}

/**
* @throws
* Updates `gitconfig` in the given `namespace` with `changedGitConfig`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { retryableExec } from '@/devworkspaceClient/services/helpers/retryableEx

export type CoreV1API = Pick<
k8s.CoreV1Api,
| 'createNamespacedConfigMap'
| 'createNamespacedSecret'
| 'listNamespace'
| 'listNamespacedEvent'
Expand All @@ -33,6 +34,8 @@ export type CoreV1API = Pick<
export function prepareCoreV1API(kc: k8s.KubeConfig): CoreV1API {
const coreV1API = kc.makeApiClient(k8s.CoreV1Api);
return {
createNamespacedConfigMap: (...args: Parameters<typeof coreV1API.createNamespacedConfigMap>) =>
retryableExec(() => coreV1API.createNamespacedConfigMap(...args)),
createNamespacedSecret: (...args: Parameters<typeof coreV1API.createNamespacedSecret>) =>
retryableExec(() => coreV1API.createNamespacedSecret(...args)),
listNamespace: (...args: Parameters<typeof coreV1API.listNamespace>) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ exports[`GitConfigUserEmail snapshot 1`] = `
>
<div>
<input
aria-invalid={true}
aria-invalid={false}
aria-label={null}
className="pf-c-form-control"
data-ouia-component-id="OUIA-Generated-TextInputBase-2"
Expand All @@ -49,7 +49,7 @@ exports[`GitConfigUserEmail snapshot 1`] = `
<span
data-testid="validated"
>
error
default
</span>
<button
aria-disabled={false}
Expand All @@ -64,13 +64,6 @@ exports[`GitConfigUserEmail snapshot 1`] = `
type="button"
/>
</div>
<div
aria-live="polite"
className="pf-c-form__helper-text pf-m-error"
id="gitconfig-user-email-helper"
>
The value is not a valid email address.
</div>
</div>
</div>
`;
Expand Down Expand Up @@ -106,7 +99,7 @@ exports[`GitConfigUserEmail snapshot, not loading 1`] = `
>
<div>
<input
aria-invalid={true}
aria-invalid={false}
aria-label={null}
className="pf-c-form-control"
data-ouia-component-id="OUIA-Generated-TextInputBase-1"
Expand All @@ -124,7 +117,7 @@ exports[`GitConfigUserEmail snapshot, not loading 1`] = `
<span
data-testid="validated"
>
error
default
</span>
<button
aria-disabled={false}
Expand All @@ -139,13 +132,6 @@ exports[`GitConfigUserEmail snapshot, not loading 1`] = `
type="button"
/>
</div>
<div
aria-live="polite"
className="pf-c-form__helper-text pf-m-error"
id="gitconfig-user-email-helper"
>
The value is not a valid email address.
</div>
</div>
</div>
`;
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,15 @@
*/

import { ValidatedOptions } from '@patternfly/react-core';
import { StateMock } from '@react-mock/state';
import userEvent from '@testing-library/user-event';
import * as React from 'react';

import getComponentRenderer, { screen } from '@/services/__mocks__/getComponentRenderer';

import { GitConfigUserEmail } from '..';
import {
GitConfigUserEmail,
State,
} from '@/pages/UserPreferences/GitConfig/Form/SectionUser/Email';
import getComponentRenderer, { screen, waitFor } from '@/services/__mocks__/getComponentRenderer';

jest.mock('@/components/InputGroupExtended');

Expand Down Expand Up @@ -67,14 +70,18 @@ describe('GitConfigUserEmail', () => {
expect(screen.getByTestId('validated')).toHaveTextContent(ValidatedOptions.error);
});

it('should re-validate on component update', () => {
const { reRenderComponent } = renderComponent('', false);

expect(screen.getByTestId('validated')).toHaveTextContent(ValidatedOptions.error);
it('should reset validation', async () => {
const localState: Partial<State> = {
value: '',
validated: ValidatedOptions.error,
};
const { reRenderComponent } = renderComponent('[email protected]', true, localState);

reRenderComponent('user@che.com', false);
reRenderComponent('user@che.org', false, localState);

expect(screen.getByTestId('validated')).toHaveTextContent(ValidatedOptions.default);
await waitFor(() =>
expect(screen.getByTestId('validated')).toHaveTextContent(ValidatedOptions.default),
);
});

it('should handle value changing', async () => {
Expand All @@ -88,6 +95,17 @@ describe('GitConfigUserEmail', () => {
});
});

function getComponent(value: string, isLoading: boolean): React.ReactElement {
function getComponent(
value: string,
isLoading: boolean,
localState?: Partial<State>,
): React.ReactElement {
if (localState) {
return (
<StateMock state={localState}>
<GitConfigUserEmail isLoading={isLoading} value={value} onChange={mockOnChange} />
</StateMock>
);
}
return <GitConfigUserEmail isLoading={isLoading} value={value} onChange={mockOnChange} />;
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,68 +28,68 @@ export type Props = {
onChange: (value: string, isValid: boolean) => void;
};
export type State = {
errorMessage?: string;
validated: ValidatedOptions | undefined;
value: string | undefined;
};

export class GitConfigUserEmail extends React.PureComponent<Props, State> {
constructor(props: Props) {
super(props);

this.state = {
validated: undefined,
validated: ValidatedOptions.default,
value: props.value,
};
}

public componentDidMount(): void {
const { value } = this.props;
this.validate(value, true);
}

public componentDidUpdate(prevProps: Readonly<Props>): void {
const { value } = this.props;
if (value !== prevProps.value) {
this.validate(value, true);
public componentDidUpdate(_prevProps: Readonly<Props>, prevState: Readonly<State>): void {
if (prevState.value === this.state.value && this.props.value !== this.state.value) {
// reset the initial value
this.setState({
value: this.props.value,
validated: ValidatedOptions.default,
});
}
}

private handleChange(value: string): void {
const isValid = this.validate(value);
const validate = this.validate(value);
const isValid = validate === ValidatedOptions.success;

this.setState({
value,
validated: validate,
});
this.props.onChange(value, isValid);
}

private validate(value: string, initial = false): boolean {
private validate(value: string): ValidatedOptions {
if (value.length === 0) {
this.setState({
errorMessage: ERROR_REQUIRED_VALUE,
validated: ValidatedOptions.error,
});
return false;
return ValidatedOptions.error;
}
if (value.length > MAX_LENGTH) {
this.setState({
errorMessage: ERROR_MAX_LENGTH,
validated: ValidatedOptions.error,
});
return false;
return ValidatedOptions.error;
}
if (!REGEX.test(value)) {
this.setState({
errorMessage: ERROR_INVALID_EMAIL,
validated: ValidatedOptions.error,
});
return false;
return ValidatedOptions.error;
}
this.setState({
errorMessage: undefined,
validated: initial === true ? ValidatedOptions.default : ValidatedOptions.success,
});
return true;
return ValidatedOptions.success;
}

public render(): React.ReactElement {
const { isLoading, value } = this.props;
const { errorMessage, validated } = this.state;
const { isLoading } = this.props;
const { value = '', validated } = this.state;

let errorMessage: string;
if (value.length === 0) {
errorMessage = ERROR_REQUIRED_VALUE;
} else if (value.length > MAX_LENGTH) {
errorMessage = ERROR_MAX_LENGTH;
} else if (!REGEX.test(value)) {
errorMessage = ERROR_INVALID_EMAIL;
} else {
errorMessage = '';
}

const fieldId = 'gitconfig-user-email';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@
*/

import { ValidatedOptions } from '@patternfly/react-core';
import { StateMock } from '@react-mock/state';
import userEvent from '@testing-library/user-event';
import * as React from 'react';

import getComponentRenderer, { screen } from '@/services/__mocks__/getComponentRenderer';

import { GitConfigUserName } from '..';
import { GitConfigUserName, State } from '@/pages/UserPreferences/GitConfig/Form/SectionUser/Name';
import getComponentRenderer, { screen, waitFor } from '@/services/__mocks__/getComponentRenderer';

jest.mock('@/components/InputGroupExtended');

Expand Down Expand Up @@ -58,14 +58,20 @@ describe('GitConfigUserName', () => {
expect(screen.getByTestId('validated')).toHaveTextContent(ValidatedOptions.error);
});

it('should re-validate on component update', () => {
const { reRenderComponent } = renderComponent('', false);
it('should reset validation', async () => {
const initialValue = 'user name';
const localState: Partial<State> = {
value: '',
validated: ValidatedOptions.error,
};

expect(screen.getByTestId('validated')).toHaveTextContent(ValidatedOptions.error);
const { reRenderComponent } = renderComponent(initialValue, true, localState);

reRenderComponent('valid name', false);
reRenderComponent(initialValue, false, localState);

expect(screen.getByTestId('validated')).toHaveTextContent(ValidatedOptions.default);
await waitFor(() =>
expect(screen.getByTestId('validated')).toHaveTextContent(ValidatedOptions.default),
);
});

it('should handle value changing', async () => {
Expand All @@ -79,6 +85,17 @@ describe('GitConfigUserName', () => {
});
});

function getComponent(value: string, isLoading: boolean): React.ReactElement {
function getComponent(
value: string,
isLoading: boolean,
localState?: Partial<State>,
): React.ReactElement {
if (localState) {
return (
<StateMock state={localState}>
<GitConfigUserName isLoading={isLoading} value={value} onChange={mockOnChange} />
</StateMock>
);
}
return <GitConfigUserName isLoading={isLoading} value={value} onChange={mockOnChange} />;
}
Loading
Loading