Skip to content

Update feature programmatically #32

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

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
8 changes: 8 additions & 0 deletions examples/simple/codeowners.config.mjs
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
/** @type {import('@codeowners-flow/cli/config').UserConfig} */
export default {
outDir: '.github',
_meta: {
defaultOwner: {
name: '@company/core-infra',
},
},
rules: [
{
/**
* Some comments
*/
patterns: ['*'],
owners: [{ name: '@company/core-team' }],
},
Expand Down
7 changes: 6 additions & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,22 @@
"dev": "tsx src/index.ts",
"lint": "eslint src",
"test": "vitest",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"test-f": "tsx test.ts"
},
"dependencies": {
"@manypkg/find-root": "2.2.1",
"cosmiconfig": "8.2.0",
"jscodeshift": "0.15.0",
"prettier": "3.0.1",
"zod": "3.21.4",
"zod-validation-error": "1.3.1"
},
"devDependencies": {
"@codeowners-flow/eslint": "workspace:*",
"@codeowners-flow/tsconfig": "workspace:*",
"@types/babel__generator": "7.6.4",
"@types/jscodeshift": "0.11.6",
"@types/node": "16",
"@vitest/coverage-v8": "0.34.1",
"eslint": "8.47.0",
Expand Down
46 changes: 3 additions & 43 deletions packages/cli/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,8 @@
import path from 'node:path';

import { cosmiconfig } from 'cosmiconfig';
import { ZodError } from 'zod';
import { fromZodError } from 'zod-validation-error';

import {
export { loadUserConfig } from './load-user-config.js';
export {
defineConfig,
defineOwner,
defineRule,
type UserConfig,
UserConfigSchema,
} from './schema.js';

const explorer = cosmiconfig('codeowners');

export async function loadUserConfig(
rootDir: string,
configRelativePath?: string,
) {
try {
const result = configRelativePath
? await explorer.load(path.resolve(rootDir, configRelativePath))
: await explorer.search();

return UserConfigSchema.parse(result?.config ?? {});
} catch (error: unknown) {
let message = 'An unexpected error occurred.';

if (error instanceof ZodError) {
const validationError = fromZodError(error as ZodError);
message = validationError.message;
} else if (error instanceof Error) {
if (error.message.includes('no such file or directory')) {
message =
'Config file not found. Please ensure to point a valid config file path or create a new one with the init command.';
} else {
message = error.message;
}
}

throw new Error(message);
}
}

export type { UserConfig };

export { defineConfig, defineOwner, defineRule };
export { updateUserConfig } from './update-config.js';
50 changes: 50 additions & 0 deletions packages/cli/src/config/load-user-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import path from 'node:path';

import { cosmiconfig } from 'cosmiconfig';
import { ZodError } from 'zod';
import { fromZodError } from 'zod-validation-error';

import { type UserConfig, UserConfigSchema } from './schema.js';

const explorer = cosmiconfig('codeowners');

type LoadUserConfigReturn = {
configPath: string;
userConfig: UserConfig;
};

export async function loadUserConfig(
rootDir: string,
configRelativePath?: string,
): Promise<LoadUserConfigReturn> {
try {
const result = configRelativePath
? await explorer.load(path.resolve(rootDir, configRelativePath))
: await explorer.search();

if (!result) {
throw new Error('no such file or directory');
}

return {
configPath: result.filepath,
userConfig: UserConfigSchema.parse(result?.config ?? {}),
};
} catch (error: unknown) {
let message = 'An unexpected error occurred.';

if (error instanceof ZodError) {
const validationError = fromZodError(error as ZodError);
message = validationError.message;
} else if (error instanceof Error) {
if (error.message.includes('no such file or directory')) {
message =
'Config file not found. Please ensure to point a valid config file path or create a new one with the init command.';
} else {
message = error.message;
}
}

throw new Error(message);
}
}
5 changes: 3 additions & 2 deletions packages/cli/src/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const OwnerSchema = z.object({
name: z.string(),
});

type Owner = z.infer<typeof OwnerSchema>;
export type Owner = z.infer<typeof OwnerSchema>;

export function defineOwner(owner: Owner) {
return owner;
Expand All @@ -17,7 +17,7 @@ const RuleSchema = z.object({
comments: z.array(z.string()).optional(),
});

type Rule = z.infer<typeof RuleSchema>;
export type Rule = z.infer<typeof RuleSchema>;

export function defineRule(rule: Rule) {
return rule;
Expand All @@ -26,6 +26,7 @@ export function defineRule(rule: Rule) {
export const UserConfigSchema = z.object({
outDir: z.string(),
rules: z.array(RuleSchema),
_meta: z.record(z.string(), z.unknown()).optional().default({}),
});

export type UserConfig = z.infer<typeof UserConfigSchema>;
Expand Down
41 changes: 41 additions & 0 deletions packages/cli/src/config/transform.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import type { API, FileInfo, Options } from 'jscodeshift';

export default function transform(
fileInfo: FileInfo,
api: API,
options: Options,
) {
const j = api.jscodeshift;
const { updatedConfig } = options;
// console.log('OSTRA', updatedConfig);

// return fileInfo.source;
const root = j(fileInfo.source);

// const a = root.find(j.Program).get('body', 0);
// const a = root.find(j.Program).get('body', 0);
// console.log(a.value.declaration.properties[0]);

root.find(j.Property).forEach((path) => {
if (
updatedConfig.outDir &&
path.getValueProperty('key').name === 'outDir'
) {
// path.setValueProperty('value', updatedConfig.outDir);

path.value.value.value = updatedConfig.outDir;
}
});

// root.find(j.Identifier).forEach((path) => {
// if (path.value.name === 'outDir') {
// console.log(path.value);
// }
// });

// a.find(j).forEach((path) => {
// console.log(path.value);
// });

return root.toSource();
}
39 changes: 39 additions & 0 deletions packages/cli/src/config/update-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// import fs from 'node:fs';
import path from 'node:path';
import * as url from 'node:url';

import { findRoot } from '@manypkg/find-root';
import { run as jscodeshift } from 'jscodeshift/src/Runner';

import { loadUserConfig } from './load-user-config.js';
import type { UserConfig } from './schema.js';

const __dirname = url.fileURLToPath(new URL('.', import.meta.url));

type UpdateUserConfigCallback = (config: UserConfig) => Partial<UserConfig>;

export async function updateUserConfig(
updateConfigCb: UpdateUserConfigCallback,
configRelativePath?: string,
) {
const { rootDir } = await findRoot(process.cwd());

const { configPath, userConfig } = await loadUserConfig(
rootDir,
configRelativePath,
);

// console.log(JSON.stringify(userConfig));
const updatedConfig = updateConfigCb(userConfig);
// const content = fs.readFileSync(configPath, 'utf8');
const transformPath = path.resolve(__dirname, './transform.ts');
console.log(
await jscodeshift(transformPath, [configPath], {
// dry: true,
print: true,
verbose: 1,
updatedConfig,
// ...
}),
);
}
28 changes: 28 additions & 0 deletions packages/cli/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { defineOwner, defineRule, type Owner } from './src/config/schema.js';
import { updateUserConfig } from './src/config/update-config.js';

await updateUserConfig((userConfig) => {
return {
outDir: '.gitlab',
rules: [
defineRule({
patterns: ['docs/*'],
owners: [
defineOwner({
name: '@gitlab-org/gitlab',
}),
(userConfig._meta as { defaultOwner: Owner }).defaultOwner,
],
}),
defineRule({
patterns: ['modules/*'],
owners: [
defineOwner({
name: '@gitlab-org/gitlab-2',
}),
(userConfig._meta as { defaultOwner: Owner }).defaultOwner,
],
}),
],
};
}, './examples/simple/codeowners.config.mjs');
Loading