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

adding a new platform to an existing project #1656

Merged
merged 6 commits into from
Aug 27, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
144 changes: 144 additions & 0 deletions packages/core/src/projects/__tests__/update.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import { checkAndUpdateProjectIfRequired } from '../update';
import path from 'path';
import { logDefault, logError, logInfo } from '../../logger';
import { getContext } from '../../context/provider';
import { generateContextDefaults } from '../../context/defaults';
import { copyFileSync, fsExistsSync, fsLstatSync, readObjectSync, writeFileSync } from '../../system/fs';
import { inquirerPrompt } from '../../api';
import { RnvPlatform } from '../../types';

jest.mock('path');
jest.mock('../../api');
jest.mock('../../context/provider');
jest.mock('../../system/fs');
jest.mock('../../logger');
jest.mock('../../templates');

afterEach(() => {
jest.resetAllMocks();
});

describe('checkAndUpdateProjectIfRequired', () => {
it('should log default message and return if platform is not defined', async () => {
// GIVEN
jest.mocked(getContext).mockReturnValue(generateContextDefaults());
//WHEN
const result = await checkAndUpdateProjectIfRequired();
//THEN
expect(logDefault).toHaveBeenCalledWith('checkAndUpdateIfRequired');
expect(result).toBeUndefined();
});
it('should return true if the project is a monorepo', async () => {
// GIVEN
jest.mocked(getContext).mockReturnValue(generateContextDefaults());
const c = getContext();
c.platform = 'ios';
c.buildConfig.isMonorepo = true;
//WHEN
const result = await checkAndUpdateProjectIfRequired();
//THEN
expect(result).toBe(true);
expect(inquirerPrompt).not.toHaveBeenCalled();
expect(writeFileSync).not.toHaveBeenCalled();
});

it('should reject if platform is not supported', async () => {
// GIVEN
jest.mocked(getContext).mockReturnValue(generateContextDefaults());
const c = getContext();
c.platform = 'test' as RnvPlatform;
c.buildConfig.isMonorepo = false;
c.files.project.config = { defaults: { supportedPlatforms: ['ios'] } };
c.paths.template.configTemplate = '/path/to/template';
jest.mocked(readObjectSync).mockReturnValue({
templateConfig: { includedPaths: [{ platforms: ['android'], paths: ['mockFile.js'] }] },
});
jest.mocked(inquirerPrompt).mockResolvedValue({ confirm: true });
//WHEN
await expect(checkAndUpdateProjectIfRequired()).rejects.toEqual('Platform test is not supported!');
//THEN
expect(logError).toHaveBeenCalledWith('Platform test is not supported!');
});
it('should reject if the user cancels the operation', async () => {
// GIVEN
jest.mocked(getContext).mockReturnValue(generateContextDefaults());
const c = getContext();
c.platform = 'android';
c.buildConfig.isMonorepo = false;
c.files.project.config = { defaults: { supportedPlatforms: ['ios'] } };
c.paths.template.configTemplate = '/path/to/template';
jest.mocked(readObjectSync).mockReturnValue({
templateConfig: { includedPaths: [{ platforms: ['android'], paths: ['mockFile.js'] }] },
});
jest.mocked(inquirerPrompt).mockResolvedValue({ confirm: false });
//WHEN
//THEN
await expect(checkAndUpdateProjectIfRequired()).rejects.toEqual('Cancelled by user');
});
it('should configure a new platform', async () => {
// GIVEN
jest.mocked(getContext).mockReturnValue(generateContextDefaults());
const c = getContext();
c.platform = 'android';
c.buildConfig.isMonorepo = false;
c.files.project.config = { defaults: { supportedPlatforms: ['ios'] } };
c.paths.project.dir = '/project/dir';
c.paths.project.config = '/project/dir/renative.json';
c.paths.template.dir = '/template/dir';
c.paths.template.configTemplate = '/path/to/template';
jest.mocked(readObjectSync).mockReturnValue({
templateConfig: { includedPaths: [{ platforms: ['android'], paths: ['mockFile.js'] }] },
});
jest.mocked(inquirerPrompt).mockResolvedValue({ confirm: true });
jest.mocked(fsExistsSync)
.mockReturnValueOnce(false)
.mockReturnValueOnce(true)
.mockReturnValueOnce(false)
.mockReturnValueOnce(true);
jest.mocked(fsLstatSync).mockReturnValue({ isDirectory: () => false } as any);
jest.mocked(path.join).mockImplementation((...paths) => paths.join('/'));
const sourcePath = path.join(c.paths.template.dir, 'mockFile.js');
const destPath = path.join(c.paths.project.dir, 'mockFile.js');

//WHEN
await expect(checkAndUpdateProjectIfRequired()).resolves.toEqual(true);
//THEN
expect(writeFileSync).toHaveBeenCalledWith('/project/dir/renative.json', {
defaults: { supportedPlatforms: ['ios', 'android'] },
});
expect(copyFileSync).toHaveBeenCalledWith(sourcePath, destPath);
expect(logInfo).toHaveBeenCalledWith(expect.stringContaining('COPYING from TEMPLATE...DONE'));
});
it('should add missing files if a new platform was added to supportedPlatforms', async () => {
// GIVEN
jest.mocked(getContext).mockReturnValue(generateContextDefaults());
const c = getContext();
c.platform = 'android';
c.buildConfig.isMonorepo = false;
c.files.project.config = { defaults: { supportedPlatforms: ['ios', 'android'] } };
c.paths.project.dir = '/project/dir';
c.paths.project.config = '/project/dir/renative.json';
c.paths.template.dir = '/template/dir';
c.paths.template.configTemplate = '/path/to/template';
jest.mocked(readObjectSync).mockReturnValue({
templateConfig: { includedPaths: [{ platforms: ['android'], paths: ['mockFile.js'] }] },
});
jest.mocked(inquirerPrompt).mockResolvedValue({ confirm: true });
jest.mocked(fsExistsSync)
.mockReturnValueOnce(false)
.mockReturnValueOnce(true)
.mockReturnValueOnce(false)
.mockReturnValueOnce(true);
jest.mocked(fsLstatSync).mockReturnValue({ isDirectory: () => false } as any);
jest.mocked(path.join).mockImplementation((...paths) => paths.join('/'));
const sourcePath = path.join(c.paths.template.dir, 'mockFile.js');
const destPath = path.join(c.paths.project.dir, 'mockFile.js');

//WHEN
await expect(checkAndUpdateProjectIfRequired()).resolves.toEqual(true);
//THEN
expect(writeFileSync).not.toHaveBeenCalled();
expect(copyFileSync).toHaveBeenCalledWith(sourcePath, destPath);
expect(logInfo).toHaveBeenCalledWith(expect.stringContaining('COPYING from TEMPLATE...DONE'));
});
});
116 changes: 116 additions & 0 deletions packages/core/src/projects/update.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import path from 'path';
import { chalk, logDefault, logError, logInfo } from '../logger';
import { getContext } from '../context/provider';
import {
copyFileSync,
copyFolderContentsRecursiveSync,
fsExistsSync,
fsLstatSync,
readObjectSync,
writeFileSync,
} from '../system/fs';
import { ConfigFileTemplate } from '../schema/types';
import { inquirerPrompt } from '../api';
import { applyTemplate } from '../templates';
import { RnvPlatform } from '../types';

export const checkAndUpdateProjectIfRequired = async () => {
logDefault('checkAndUpdateIfRequired');
const c = getContext();
const { platform } = c;
const supportedPlatforms = c.files.project.config?.defaults?.supportedPlatforms;

if (!platform) return;
const { isMonorepo } = c.buildConfig;
if (isMonorepo) return true;
await applyTemplate();

const templateConfigFile = readObjectSync<ConfigFileTemplate>(c.paths.template.configTemplate);

if (templateConfigFile) {
const availablePlatforms = _getAllAvailablePlatforms(templateConfigFile);
if (!availablePlatforms.includes(platform)) {
logError(`Platform ${platform} is not supported!`);
return Promise.reject(`Platform ${platform} is not supported!`);
} else {
const missingFiles = _getMisFilesForPlatform({
templateConfigFile,
platform,
projectPath: c.paths.project.dir,
templatePath: c.paths.template.dir,
});
if (missingFiles.length || !supportedPlatforms?.includes(platform)) {
const { confirm } = await inquirerPrompt({
type: 'confirm',
message: `You are trying to run platform ${chalk().bold.magenta(
platform
)} which is not configured. Do you want to configure it now?`,
});
if (!confirm) {
return Promise.reject('Cancelled by user');
}

if (supportedPlatforms) {
if (!supportedPlatforms.includes(platform)) {
supportedPlatforms.push(platform);
if (c.files.project.config) {
writeFileSync(c.paths.project.config, c.files.project.config);
}
}
}

missingFiles.forEach((mf) => {
const destPath = path.join(c.paths.project.dir, mf);
const sourcePath = path.join(c.paths.template.dir, mf);

if (!fsExistsSync(destPath) && fsExistsSync(sourcePath)) {
try {
if (fsLstatSync(sourcePath).isDirectory()) {
logInfo(
`Missing directory ${chalk().bold.white(destPath)}. COPYING from TEMPLATE...DONE`
);
copyFolderContentsRecursiveSync(sourcePath, destPath);
} else {
logInfo(`Missing file ${chalk().bold.white(destPath)}. COPYING from TEMPLATE...DONE`);
copyFileSync(sourcePath, destPath);
}
} catch (e) {
console.log(e);
}
}
});
}
}
}

return true;
};
const _getAllAvailablePlatforms = (templateConfigFile: ConfigFileTemplate): string[] => {
const includedPaths = templateConfigFile.templateConfig?.includedPaths || [];
return includedPaths.reduce((acc, item) => {
if (typeof item !== 'string' && item.platforms) {
acc.push(...item.platforms);
}
return acc;
}, [] as string[]);
};
const _getMisFilesForPlatform = (opts: {
templateConfigFile: ConfigFileTemplate;
platform: RnvPlatform;
projectPath: string;
templatePath: string;
}) => {
const { templateConfigFile, platform, projectPath, templatePath } = opts;
const includedPaths = templateConfigFile.templateConfig?.includedPaths || [];
const result = includedPaths.find(
(item) => typeof item !== 'string' && item.platforms && item.platforms.includes(platform!)
);

if (result && typeof result !== 'string') {
const nonExistingFiles = result.paths.filter(
(file) => !fsExistsSync(path.join(projectPath, file)) && fsExistsSync(path.join(templatePath, file))
);
return nonExistingFiles;
}
return [];
};
3 changes: 2 additions & 1 deletion packages/core/src/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { runInteractiveWizard } from './tasks/wizard';
import { initializeTask } from './tasks/taskExecutors';
import { getTaskNameFromCommand, selectPlatformIfRequired } from './tasks/taskHelpers';
import { logInfo } from './logger';
import { checkAndUpdateProjectIfRequired } from './projects/update';

export const exitRnvCore = async (code: number) => {
const ctx = getContext();
Expand Down Expand Up @@ -40,7 +41,7 @@ export const executeRnvCore = async () => {
await configureRuntimeDefaults();
await checkAndMigrateProject();
await updateRenativeConfigs();
// await checkAndBootstrapIfRequired();
await checkAndUpdateProjectIfRequired();

// TODO: rename to something more meaningful or DEPRECATE entirely
if (c.program.opts().npxMode) {
Expand Down
11 changes: 4 additions & 7 deletions packages/template-starter/renative.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@
"MainActivity_kt": {
"onCreate": "super.onCreate(savedInstanceState)"
}
}
},
"engine": "engine-rn"
},
"androidtv": {
"extendPlatform": "android",
Expand All @@ -83,9 +84,7 @@
"minSdkVersion": 21,
"extendPlatform": "android",
"engine": "engine-rn-tvos",
"includedPermissions": [
"INTERNET"
]
"includedPermissions": ["INTERNET"]
},
"web": {
"engine": "engine-rn-next"
Expand All @@ -100,9 +99,7 @@
"engine": "engine-rn-electron",
"assetFolderPlatform": "electron",
"webpackConfig": {
"excludedPaths": [
"pages"
]
"excludedPaths": ["pages"]
}
},
"windows": {
Expand Down
45 changes: 10 additions & 35 deletions packages/template-starter/renative.template.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,35 +20,15 @@
]
},
{
"paths": [
"Gemfile",
"metro.config.js",
".bundle",
"react-native.config.js"
],
"platforms": [
"ios",
"android",
"androidwear",
"tvos",
"firetv",
"androidtv"
]
"paths": ["Gemfile", "metro.config.js", ".bundle", "react-native.config.js"],
"platforms": ["ios", "android", "androidwear", "tvos", "firetv", "androidtv"]
},
{
"paths": [
"next.config.js",
"next-env.d.ts",
"src/pages"
],
"platforms": [
"web"
]
"paths": ["next.config.js", "next-env.d.ts", "src/pages"],
"platforms": ["web"]
},
{
"paths": [
"webpack.config.js"
],
"paths": ["webpack.config.js"],
"platforms": [
"windows",
"macos",
Expand Down Expand Up @@ -79,23 +59,18 @@
"@rnv/adapter": "1.0.0",
"@rnv/config-templates": "1.0.0",
"babel-loader": "9.1.3",
"dotenv": "16.4.5"
"dotenv": "16.4.5",
"minipass": "7.1.2",
"readable-stream": "4.5.2"
},
"browserslist": [
">0.2%",
"not op_mini all"
]
"browserslist": [">0.2%", "not op_mini all"]
}
},
"bootstrapConfig": {
"rnvNewPatchDependencies": {
"pkg-dir": "7.0.0",
"xmlbuilder": "^15.1.1"
},
"defaultSelectedPlatforms": [
"web",
"ios",
"android"
]
"defaultSelectedPlatforms": ["web", "ios", "android"]
}
}
Loading