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 debugging option #62

Merged
merged 3 commits into from
Oct 12, 2023
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: 3 additions & 6 deletions deno.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"zod": "https://deno.land/x/zod@v3.20.1/mod.ts",
"rambda": "https://mckgnjtrq3abdh6fhic5ddwopjdoxtpu2vvkyphhzwui4egizoma.arweave.net/YJRmpnGGwBGfxToF0Y7OekbrzfTVaqw8582ojhDIy5g/mod.ts",
"memoizy": "https://deno.land/x/memoizy@1.0.0/mod.ts",
"logger": "https://deno.land/x/logger@v1.1.1/logger.ts",
"version": "./version.ts",
"commands/config": "./src/commands/config/mod.ts",
"models/repository": "./src/models/repository/mod.ts",
Expand All @@ -20,11 +21,7 @@
}
},
"fmt": {
"files": {
"exclude": ["dist"]
},
"options": {
"singleQuote": true
}
"singleQuote": true,
"exclude": ["dist"]
}
}
14 changes: 13 additions & 1 deletion deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 12 additions & 2 deletions src/commands/add.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,47 @@
import { EOL } from 'std/fs';
import { basename } from 'std/path';
import { Checkbox, colors, Command } from 'cliffy';
import { logger } from 'lib';
import { getConfig, RepoType, setConfig } from '../config.ts';
import { getAuthors } from '../git.ts';

export default new Command()
.description('Add one or more local repositories for syncing.')
.arguments('<...repositories:string>')
.option('-e, --email <email:string>', 'Email to sync', { collect: true })
.action(async (_, ...repoPaths) => {
.option('-d, --debug', 'Enable debug output.')
.action(async ({ debug }, ...repoPaths) => {
if (debug) logger.enable();

logger.info('Adding following repositories:', repoPaths);
const config = await getConfig();

logger.info('Current config:', config);
const mutableConfig = { ...config };

for (const repoPath of repoPaths) {
const authors = await getAuthors(repoPath);
logger.info('Authors:', authors);

const selectedAuthors: string[] = await Checkbox.prompt({
message: `Select authors of commits to extract from the "${
basename(repoPath)
} repository". Use arrow keys for navigation, space to select, and enter to submit.`,
options: authors.map((author) => `${author.name} <${author.email}>`),
});
logger.info('Selected authors:', selectedAuthors);

const repo: RepoType = {
dir: repoPath,
authors: authors.filter((author) =>
selectedAuthors.includes(`${author.name} <${author.email}>`)
),
};
logger.info('Repository details:', repo);

mutableConfig.repos[basename(repoPath)] = repo;
}

logger.info('Setting new config:', mutableConfig);
await setConfig(mutableConfig);

console.log(
Expand Down
24 changes: 22 additions & 2 deletions src/commands/sync.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { colors, Command, Select } from 'cliffy';
import { join } from 'std/path';
import { ghNoReplyCheck, promptAllInputs, validate } from 'lib';
import { ghNoReplyCheck, logger, promptAllInputs, validate } from 'lib';
import { getConfig, getConfigDir, setConfig } from '../config.ts';
import {
AuthorSchema,
Expand All @@ -22,11 +22,17 @@ const SYNC_REPO_PATH = join(getConfigDir(), 'sync-repo');

export default new Command()
.description('Synchronize commits from local repositories to GitHub profile.')
.action(async () => {
.option('-d, --debug', 'Enable debug output.')
.action(async ({ debug }) => {
if (debug) logger.enable();

let config = await getConfig();
logger.info('Current config:', config);

if (!config.syncRepo) {
logger.info('No sync repository found. Cloning one...');
const repos = await getRepositories();
logger.info('Found repositories:', repos);

const id = await Select.prompt({
message: 'Choose a repository to sync commits to:',
Expand All @@ -35,15 +41,23 @@ export default new Command()
options: repos.map((repo) => ({ value: repo.id, name: repo.name })),
});
const selectedRepo = repos.find((repo) => repo.id === id);
logger.info('Selected repository:', selectedRepo);
await cloneRepository(selectedRepo!, 'sync-repo', getConfigDir());
await setConfig({ syncRepo: selectedRepo });
config = await getConfig();
logger.info('New config:', config);
} else {
logger.info('Sync repository found. Pulling latest changes...');
await pullRepositoryChanges(SYNC_REPO_PATH);
}

if (!config.author) {
logger.info('No author found. Prompting one...');
const currentGitAuthor = await getGitAuthor();
logger.info(
'Current git author configured in git config:',
currentGitAuthor,
);
const [name, email] = await promptAllInputs(
Object.keys(AuthorSchema.shape).map((key) => ({
message: `Authoring ${key}:`,
Expand All @@ -59,11 +73,14 @@ export default new Command()
ghNoReplyCheck(email);

const author: AuthorType = { name, email };
logger.info('Selected author:', { name, email });
await setConfig({ author });
config = await getConfig();
logger.info('New config:', config);
}

const history = await getGitHistory(SYNC_REPO_PATH);
logger.info('Current history:', history);
const authorsWithDirs: Array<AuthorType & { dir: string }> = Object.values(
config.repos,
).flatMap((repo) =>
Expand All @@ -76,6 +93,7 @@ export default new Command()
)).flat().filter((commit) =>
!history.some((entry) => entry?.hash === commit.hash)
);
logger.info('New commits:', commits);

if (!commits.length) {
console.log('No new commits to synchronize. Exiting...');
Expand All @@ -88,12 +106,14 @@ export default new Command()
);

commits.forEach((commit) => {
logger.info('Creating commit:', commit);
createCommit(
{ ...commit, author: config.author! },
SYNC_REPO_PATH,
);
});

logger.info('Pushing changes to sync repository...');
await pushRepositoryChanges(SYNC_REPO_PATH);

console.log(
Expand Down
2 changes: 2 additions & 0 deletions src/gh.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { z } from 'zod';
import { logger } from 'lib';

export const RepositorySchema = z.object({
id: z.string().trim(),
Expand Down Expand Up @@ -59,6 +60,7 @@ export async function pullRepositoryChanges(

if (cmdOutput.code !== 0) throw new TextDecoder().decode(cmdOutput.stderr);
} catch (err) {
logger.error('Pulling repository changes failed:', err);
// with a clean repo there are no changes to pull yet
if (typeof err != 'string' || !err.includes('invalid refspec')) throw err;
}
Expand Down
4 changes: 3 additions & 1 deletion src/git.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { z } from 'zod';
import { logger } from 'lib';

export const AuthorSchema = z.object({
name: z.string().min(1).trim(),
Expand Down Expand Up @@ -75,7 +76,8 @@ export async function getGitAuthor(): Promise<AuthorType | undefined> {

try {
return AuthorSchema.parse({ name, email });
} catch (_) { // todo: debugger
} catch (err) {
logger.error('Failed to parse git author:', err);
return;
}
}
Expand Down
7 changes: 7 additions & 0 deletions src/lib/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import Logger from 'logger';

const logger = new Logger();

logger.disable();

export { logger };
1 change: 1 addition & 0 deletions src/lib/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export { validate } from './validate.ts';
export { promptAllInputs } from './promptAllInputs.ts';
export { ghNoReplyCheck } from './ghNoReplyCheck.ts';
export { ensurePath } from './ensurePath.ts';
export { logger } from './logger.ts';
1 change: 1 addition & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ await new Command()
.action(function (this: Command) {
this.showHelp();
})
.option('-d, --debug', 'Enable debug output.', { global: true })
.command('add', add)
.command('sync', sync)
.parse(Deno.args);