Skip to content

Commit

Permalink
feat: dynamic branch on init if using default main which does not e…
Browse files Browse the repository at this point in the history
…xist (#1173)
  • Loading branch information
eemmiillyy authored Sep 15, 2023
1 parent 5daf697 commit c2885ad
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 10 deletions.
5 changes: 5 additions & 0 deletions .changeset/famous-stingrays-stare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@xata.io/cli': patch
---

Add ability to interactively select branch on xata init when main branch does not exist
12 changes: 11 additions & 1 deletion cli/src/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -346,14 +346,24 @@ export abstract class BaseCommand<T extends typeof Command> extends Command {
workspace: string,
region: string,
database: string,
options: { allowEmpty?: boolean; allowCreate?: boolean; title?: string } = {}
options: {
allowEmpty?: boolean;
allowCreate?: boolean;
title?: string;
// Branch to default if exists
defaultBranch?: string;
} = {}
): Promise<string> {
const xata = await this.getXataClient();
const { branches = [] } = await xata.api.branches.getBranchList({ workspace, region, database });

const EMPTY_CHOICE = '$empty';
const CREATE_CHOICE = '$create';

if (options.defaultBranch && branches.map(({ name }) => name).includes(options.defaultBranch)) {
return options.defaultBranch;
}

if (branches.length > 0) {
const choices = branches.map((db) => ({
title: db.name,
Expand Down
4 changes: 2 additions & 2 deletions cli/src/commands/codegen/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export default class Codegen extends BaseCommand<typeof Codegen> {
this.log(`Generated Xata code to ./${relative(process.cwd(), output)}`);
}

static async runIfConfigured(projectConfig?: ProjectConfig) {
if (projectConfig?.codegen?.output) return Codegen.run([]);
static async runIfConfigured(projectConfig?: ProjectConfig, flags?: any[]) {
if (projectConfig?.codegen?.output) return Codegen.run(flags ?? []);
}
}
10 changes: 9 additions & 1 deletion cli/src/commands/init/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,16 @@ const fetchImplementation = (url: string, request: any) => {
ok: true,
json: async () => ({ meta: { cursor: '', more: false }, logs: [] })
};
} else if (url === `https://test-1234.${REGION}.xata.sh/dbs/db1` && request.method === 'GET') {
return {
ok: true,
json: async () => {
return {
branches: [{ name: 'main', id: 'main' }]
};
}
};
}

throw new Error(`Unexpected fetch request: ${url} ${request.method}`);
};

Expand Down
23 changes: 17 additions & 6 deletions cli/src/commands/init/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ const packageManagers = {
}
};

const DEFAULT_BRANCH = 'main';

const isPackageManagerInstalled = (packageManager: PackageManager) =>
which.sync(packageManager.command, { nothrow: true });

Expand Down Expand Up @@ -134,6 +136,16 @@ export default class Init extends BaseCommand<typeof Init> {

const { workspace, region, database, databaseURL } = await this.getParsedDatabaseURL(flags.db, true);

const detectedBranch = this.getCurrentBranchName();
const branch =
detectedBranch === DEFAULT_BRANCH
? await this.getBranch(workspace, region, database, {
allowCreate: false,
allowEmpty: false,
defaultBranch: DEFAULT_BRANCH
})
: detectedBranch;

this.projectConfig = { databaseURL };
const ignoreEnvFile = await this.promptIgnoreEnvFile();

Expand All @@ -146,7 +158,7 @@ export default class Init extends BaseCommand<typeof Init> {
await this.writeConfig();
this.log();

await this.writeEnvFile(workspace, region, database);
await this.writeEnvFile(workspace, region, database, branch);

if (ignoreEnvFile) {
await this.ignoreEnvFile();
Expand All @@ -157,14 +169,13 @@ export default class Init extends BaseCommand<typeof Init> {
await this.installPackage(packageManager, '@xata.io/client');
}

const branch = this.getCurrentBranchName();
if (schema) {
await this.deploySchema(workspace, region, database, branch, schema);
}

// Run pull to retrieve remote migrations, remove any local migrations, and generate code
await Pull.run([branch, '-f', '--skip-code-generation']);
await Codegen.runIfConfigured(this.projectConfig);
await Codegen.runIfConfigured(this.projectConfig, [`--branch=${branch}`]);

await this.delay(1000);

Expand Down Expand Up @@ -194,7 +205,7 @@ export default class Init extends BaseCommand<typeof Init> {
}columns at https://app.xata.io/workspaces/${workspace}/dbs/${database}:${region}`
);
this.log();
this.info(`Use ${chalk.bold(`xata pull main`)} to regenerate code and types from your Xata database`);
this.info(`Use ${chalk.bold(`xata pull ${branch}`)} to regenerate code and types from your Xata database`);
} else {
this.log(`To make your first query:`);
this.log(``);
Expand Down Expand Up @@ -375,7 +386,7 @@ export default class Init extends BaseCommand<typeof Init> {
return envFile;
}

async writeEnvFile(workspace: string, region: string, database: string) {
async writeEnvFile(workspace: string, region: string, database: string, branch: string) {
const envFile = await this.findEnvFile();
const doesEnvFileExist = await this.access(envFile);

Expand All @@ -398,7 +409,7 @@ export default class Init extends BaseCommand<typeof Init> {
if (containsXataApiKey) {
this.warn(`Your ${envFile} file already contains XATA_API_KEY key. skipping...`);
} else {
const setBranch = `XATA_BRANCH=main`;
const setBranch = `XATA_BRANCH=${branch}`;
if (content) content += '\n\n';
content += '# [Xata] Configuration used by the CLI and the SDK\n';
content += '# Make sure your framework/tooling loads this file on startup to have it available for the SDK\n';
Expand Down

0 comments on commit c2885ad

Please sign in to comment.