Skip to content

Commit

Permalink
feat: add new init command
Browse files Browse the repository at this point in the history
  • Loading branch information
rams23 committed Oct 26, 2023
1 parent e5865c7 commit ff6caa0
Show file tree
Hide file tree
Showing 8 changed files with 187 additions and 29 deletions.
2 changes: 2 additions & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"axios": "^1.3.4",
"chalk": "^4.1.2",
"dotenv": "^16.3.1",
"inquirer": "^9.2.11",
"ios-deploy": "^1.12.1",
"open": "^8.4.2",
"prompts": "^2.4.2"
Expand All @@ -46,6 +47,7 @@
"@rn-buildhub/s3-storage": "workspace:^",
"@types/adm-zip": "^0.5.0",
"@types/chai": "^4",
"@types/inquirer": "^9.0.6",
"@types/mocha": "^9.0.0",
"@types/node": "^18.18.4",
"@types/prompts": "^2.4.2",
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/application/cloud/projectsManagement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export type RemoteConfig = {
export type ProjectConfiguration = {
remote: RemoteConfig;
// this should not stay at project level because it indicates the build that the user has locally
currentBuildId: string | null;
currentBuildId?: string | null;
};


Expand Down
7 changes: 5 additions & 2 deletions packages/cli/src/application/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,15 @@ export function executeCommandAsync(command: string, options?: ExecSyncOptionsWi
return execAsync(command, options);
}

export function getRootDestinationFolderBaseName() {
return ".rn-buildhub";
}
export function getRootDestinationFolder() {
return path.join(getProjectRootDir(), ".rn-build-hub");
return path.join(getProjectRootDir(), getRootDestinationFolderBaseName());
}

export function getConfigFile() {
return path.join(getProjectRootDir(), ".rn-build-hub.json");
return path.join(getProjectRootDir(), ".rn-buildhub.json");
}

export function getProjectRootDir() {
Expand Down
92 changes: 92 additions & 0 deletions packages/cli/src/commands/init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { Command, Flags } from "@oclif/core";
import fs from "fs";
import { getConfigFile, getProjectRootDir, getRootDestinationFolderBaseName } from "../application/utils";
import logger from "../application/logger";
import { ProjectConfiguration } from "../application/cloud/projectsManagement";
import path from "path";

const remoteMapping = {
azure: "@rn-buildhub/azure-storage",
aws: "@rn-buildhub/s3-storage",
gcp: "@rn-buildhub/gcp-storage"
};


function addDevDepsToPackageJson(deps: Record<string, string>) {
const packageJsonPath = path.join(getProjectRootDir(), "package.json");
if (fs.existsSync(packageJsonPath)) {
const packageJson = JSON.parse(fs.readFileSync("package.json", "utf8"));
packageJson.devDependencies = {
...(packageJson.devDependencies || {}),
...deps
};
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
}

}

export default class Init extends Command {
static description = "Create native builds for android and ios";

static examples = [
"<%= config.bin %> <%= command.id %> -i -f=dev",
"<%= config.bin %> <%= command.id %> -a -f=prod",
"<%= config.bin %> <%= command.id %> -a -f=prod --release",
"<%= config.bin %> <%= command.id %> -a --release",
"<%= config.bin %> <%= command.id %> -a --incremental"
];

static flags = {
remote: Flags.string({
char: "r", description: "The remote storage to use",
options: ["azure", "aws", "gcp"]
})
};

public async run(): Promise<void> {
const { flags } = await this.parse(Init);
// check if already initialized by checking if .rn-buildhub.json exists
if (fs.existsSync(getConfigFile())) {
this.error("Already initialized");
}
let remote = flags.remote;
if (!remote) {
const { default: inquirer } = await import("inquirer");
let responses: any = await inquirer.prompt([{
name: "remote",
message: "select a remote storage to use",
type: "list",
choices: [{ name: "azure" }, { name: "aws" }, { name: "gcp" }]
}]);
remote = responses.remote;
}
if (remote && remote in remoteMapping) {
const remotePackage = remoteMapping[remote as keyof typeof remoteMapping];
logger.info(`Updating package.json with ${remotePackage} and @rn-buildhub/cli`);
logger.info(`Please install ${remotePackage} with your package manager`);

const version = this.config.version;

addDevDepsToPackageJson({
'@rn-buildhub/cli': `^${version}`,
[remotePackage]: `^${version}`
});
// create the config file and write it
const config: ProjectConfiguration = {
remote: {
name: remotePackage,
config: {}
}
};
logger.info(`Creating configuration file ${getConfigFile()}`);
fs.writeFileSync(getConfigFile(), JSON.stringify(config, null, 2));
}
// append to gitignore .rn-buildhub if gitignore exists
if (fs.existsSync(".gitignore")) {
logger.info(`Adding build cache folder to .gitignore`);
fs.appendFileSync(".gitignore", `${getRootDestinationFolderBaseName()}`);
}

this.exit(0);
}
}
6 changes: 3 additions & 3 deletions packages/cli/src/commands/run.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Args, Command, Flags } from '@oclif/core';
import { Flags } from '@oclif/core';
import { runApp as runAndroid } from '../application/runAndroid';
import { runApp as runIos } from '../application/runIos';
import { startMetro, checkIsMetroRunning } from '../application/metroManager';
import logger from '../application/logger';
import { iosBuildPlatforms } from '../application/iosUtils';
import { downloadBuildIfNotPresent, updateCurrentBuild } from "./makeBuildCurrent";
import { downloadBuildIfNotPresent } from "./makeBuildCurrent";
import RemoteAwareCommand from '../_projectAwareCommand';

export default class Run extends RemoteAwareCommand {
Expand All @@ -18,7 +18,7 @@ export default class Run extends RemoteAwareCommand {
flavor: Flags.string({ char: 'f', description: 'Specify the android flavor or the ios scheme to build' }),
verbose: Flags.boolean({ description: 'Verbose output' }),
forceBuild: Flags.boolean({ aliases: ['fb', 'force-build'], description: 'Force a native rebuild' }),
buildId: Flags.string({ description: 'Specify the build id. Can be local, last or a buildId', default: undefined }),
buildId: Flags.string({ aliases: ['id'], description: 'Specify the build id. Can be local, last or a buildId', default: undefined }),
};

static args = {
Expand Down
4 changes: 3 additions & 1 deletion packages/cli/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@
"declaration": true,
"importHelpers": true,
"module": "commonjs",
"moduleResolution": "Node16",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"noImplicitAny": true,
"noEmitOnError": true,
"target": "es2019",
"esModuleInterop": true,
"skipLibCheck": true
"skipLibCheck": true,
"resolveJsonModule": true
},
"include": [
"src/**/*"
Expand Down
4 changes: 2 additions & 2 deletions packages/storage-azure/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const ENV_AZURE_AD_AUTH = "RNBH_AZURE_AD_AUTH";

const getEnv = (key: string) => process.env[key];

function getBlockBlobClient(filename: string, options: AzureBlobRunnerOptions) {
function getBlockBlobClient(filename: string, options: AzureBlobRunnerOptions = {}) {
const connectionString = getEnv(ENV_CONNECTION_STRING) ?? options.connectionString;
const accountKey = getEnv(ENV_ACCOUNT_KEY) ?? options.accountKey;
const accountName = getEnv(ENV_ACCOUNT_NAME) ?? options.accountName;
Expand Down Expand Up @@ -72,7 +72,7 @@ class AzureStorage extends RemoteStorage {
private blob: (filename: string) => BlockBlobClient;

// todo validate config
constructor(config: object) {
constructor(config?: object) {
super();
require("dotenv").config({ path: path.join(getProjectRootDir(), ".env") });
this.blob = (filename: string) => getBlockBlobClient(filename, config);
Expand Down
Loading

0 comments on commit ff6caa0

Please sign in to comment.