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

add changes commit command #23

Merged
merged 5 commits into from
Oct 6, 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
9 changes: 5 additions & 4 deletions src/app.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import React from 'react';
import { Box, Text } from 'ink';
import { PropValidationResult } from './types.js';
import { type Result } from 'meow';
import { findCommand } from './utils/commands.js';

type Props = {
readonly cli: Result<any>;

Check warning on line 8 in src/app.tsx

View workflow job for this annotation

GitHub Actions / lint_test

Unexpected any. Specify a different type
};

export default function App({ cli }: Props) {
Expand All @@ -23,21 +24,21 @@
);
}

const { valid, errors } = command.config.validateProps
const validationResult = command.config.validateProps
? command.config.validateProps({
cli,
input: cli.input,
})
: { valid: true, errors: [] };
: ({ valid: true } as PropValidationResult);

if (!valid) {
if (!validationResult.valid) {
return (
<Box flexDirection="column">
<Text>
Invalid inputs for command:{' '}
<Text color="red">{sanitizedInput.join(' ')}</Text>
</Text>
{errors?.map((error) => (
{validationResult.errors.map((error) => (
<Text key={error}>
- <Text color="red">{error}</Text>
</Text>
Expand Down
7 changes: 7 additions & 0 deletions src/command-registry.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import ChangesAdd, { changesAddConfig } from './commands/changes/add.js';
import ChangesCommit, {
changesCommitConfig,
} from './commands/changes/commit.js';
import Help, { helpConfig } from './commands/help.js';
import Hop, { hopConfig } from './commands/hop.js';
import Sync, { syncConfig } from './commands/sync.js';
Expand Down Expand Up @@ -31,5 +34,9 @@ export const REGISTERED_COMMANDS: CommandGroup = {
component: ChangesAdd,
config: changesAddConfig,
},
commit: {
component: ChangesCommit,
config: changesCommitConfig,
},
} as CommandGroup,
} as const;
101 changes: 101 additions & 0 deletions src/commands/changes/commit.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import ChangesCommit from './commit.js';
import React from 'react';
import { Text } from 'ink';
import { delay } from '../../utils/time.js';
import { describe, expect, it, vi } from 'vitest';
import { render } from '@levelbreaded/ink-testing-library';

const ARBITRARY_DELAY = 250; // ms

const mocks = vi.hoisted(() => {
return {
createGitService: vi.fn(({}) => {
return {
commit: async ({ message }: { message: string }) => {
console.log(message);
return new Promise((resolve) =>
setTimeout(resolve, ARBITRARY_DELAY)
);
},
};
}),
};
});

vi.mock('../../services/git.js', () => {
return {
DEFAULT_OPTIONS: {},
createGitService: mocks.createGitService,
};
});

const LOADING_MESSAGE = 'Loading...';
const SUCCESS_MESSAGE = 'Committed all changes';

describe('correctly renders changes commit UI', () => {
it('runs as intended', async () => {
const actual1 = render(
<ChangesCommit
cli={{
flags: {},
unnormalizedFlags: {},
}}
input={['changes', 'commit', 'commit message']}
/>
);

const actual2 = render(
<ChangesCommit
cli={{
flags: {},
unnormalizedFlags: {},
}}
input={['changes', 'c', 'commit message']}
/>
);

const ExpectedComp = () => {
return (
<Text bold color="green">
{SUCCESS_MESSAGE}
</Text>
);
};
const expected = render(<ExpectedComp />);

await delay(ARBITRARY_DELAY + 250);
expect(actual1.lastFrame()).to.equal(expected.lastFrame());
expect(actual2.lastFrame()).to.equal(expected.lastFrame());
});

it('displays a loading state while processing', async () => {
const actual1 = render(
<ChangesCommit
cli={{
flags: {},
unnormalizedFlags: {},
}}
input={['changes', 'commit', 'commit message']}
/>
);

const actual2 = render(
<ChangesCommit
cli={{
flags: {},
unnormalizedFlags: {},
}}
input={['changes', 'c', 'commit message']}
/>
);

const ExpectedComp = () => {
return <Text color="cyan">{LOADING_MESSAGE}</Text>;
};
const expected = render(<ExpectedComp />);

await delay(ARBITRARY_DELAY / 2);
expect(actual1.lastFrame()).to.equal(expected.lastFrame());
expect(actual2.lastFrame()).to.equal(expected.lastFrame());
});
});
94 changes: 94 additions & 0 deletions src/commands/changes/commit.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import ErrorDisplay from '../../components/error-display.js';
import React, { useEffect, useState } from 'react';
import { CommandConfig, CommandProps } from '../../types.js';
import { Text } from 'ink';
import { useGit } from '../../hooks/use-git.js';

function ChangesCommit({ input }: CommandProps) {
const [, , message] = input;
// todo: refactor to a sanitize input pattern
const result = useChangesCommit({ message: message! });

if (result.isError) {
return <ErrorDisplay error={result.error} />;
}

if (result.isLoading) {
return <Text color="cyan">Loading...</Text>;
}

return (
<Text bold color="green">
Committed all changes
</Text>
);
}

type Action = { isLoading: boolean } & (
| {
isError: false;
}
| {
isError: true;
error: Error;
}
);

type State =
| {
type: 'LOADING';
}
| {
type: 'COMPLETE';
}
| {
type: 'ERROR';
error: Error;
};

const useChangesCommit = ({ message }: { message: string }): Action => {
const git = useGit();
const [state, setState] = useState<State>({ type: 'LOADING' });

useEffect(() => {
git.commit({ message })
.then(() => setState({ type: 'COMPLETE' }))
.catch((e: Error) => {
setState({ type: 'ERROR', error: e });
});
}, []);

if (state.type === 'ERROR') {
return {
isLoading: false,
isError: true,
error: state.error,
};
}

return {
isLoading: state.type === 'LOADING',
isError: false,
};
};

export const changesCommitConfig: CommandConfig = {
description: 'Stage and commit all changes.',
usage: 'changes commit "<message>"',
key: 'commit',
aliases: ['c'],
validateProps: (props) => {
const { input } = props;
const [, , message] = input;

if (!message)
return {
valid: false,
errors: ['Please provide a commit message'],
};

return { valid: true };
},
};

export default ChangesCommit;
4 changes: 4 additions & 0 deletions src/services/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface GitService {
branchLocal: () => Promise<ReturnType<SimpleGit['branchLocal']>>;
checkout: (branch: string) => Promise<ReturnType<SimpleGit['checkout']>>;
addAllFiles: () => Promise<void>;
commit: (args: { message: string }) => Promise<void>;
}

export const createGitService = ({
Expand All @@ -33,5 +34,8 @@ export const createGitService = ({
addAllFiles: async () => {
await gitEngine.add('.');
},
commit: async ({ message }) => {
await gitEngine.commit(message);
},
};
};
13 changes: 9 additions & 4 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import { ComponentType } from 'react';
import { Result } from 'meow';

type ValidateProps<T extends Record<string, unknown>> = (props: T) => {
valid: boolean;
errors?: string[];
};
export type ValidateProps<T extends Record<string, unknown>> = (
props: T
) => PropValidationResult;

export type PropValidationResult =
| {
valid: true;
}
| { valid: false; errors: string[] };

export interface CommandProps extends Record<string, unknown> {
cli: Pick<Result<any>, 'flags' | 'unnormalizedFlags'>;

Check warning on line 15 in src/types.ts

View workflow job for this annotation

GitHub Actions / lint_test

Unexpected any. Specify a different type
input: string[];
}

Expand Down