This commit is contained in:
Yamozha
2021-04-02 02:24:13 +03:00
parent c23950b545
commit 7256d79e2c
31493 changed files with 3036630 additions and 0 deletions

View File

@ -0,0 +1,187 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _chalk() {
const data = _interopRequireDefault(require("chalk"));
_chalk = function () {
return data;
};
return data;
}
function _path() {
const data = _interopRequireDefault(require("path"));
_path = function () {
return data;
};
return data;
}
var _copyAndReplace = _interopRequireDefault(require("../copyAndReplace"));
var _promptSync = _interopRequireDefault(require("./promptSync"));
var _walk = _interopRequireDefault(require("../walk"));
function _cliTools() {
const data = require("@react-native-community/cli-tools");
_cliTools = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
const prompt = (0, _promptSync.default)();
/**
* Util for creating a new React Native project.
* Copy the project from a template and use the correct project name in
* all files.
* @param srcPath e.g. '/Users/martin/AwesomeApp/node_modules/react-native/template'
* @param destPath e.g. '/Users/martin/AwesomeApp'
* @param newProjectName e.g. 'AwesomeApp'
* @param options e.g. {
* upgrade: true,
* force: false,
* displayName: 'Hello World',
* ignorePaths: ['template/file/to/ignore.md'],
* }
*/
function copyProjectTemplateAndReplace(srcPath, destPath, newProjectName, options = {}) {
if (!srcPath) {
throw new Error('Need a path to copy from');
}
if (!destPath) {
throw new Error('Need a path to copy to');
}
if (!newProjectName) {
throw new Error('Need a project name');
}
(0, _walk.default)(srcPath).forEach(absoluteSrcFilePath => {
// 'react-native upgrade'
if (options.upgrade) {
// Don't upgrade these files
const fileName = _path().default.basename(absoluteSrcFilePath); // This also includes __tests__/index.*.js
if (fileName === 'index.ios.js') {
return;
}
if (fileName === 'index.android.js') {
return;
}
if (fileName === 'index.js') {
return;
}
if (fileName === 'App.js') {
return;
}
}
const relativeFilePath = translateFilePath(_path().default.relative(srcPath, absoluteSrcFilePath)).replace(/HelloWorld/g, newProjectName).replace(/helloworld/g, newProjectName.toLowerCase()); // Templates may contain files that we don't want to copy.
// Examples:
// - Dummy package.json file included in the template only for publishing to npm
// - Docs specific to the template (.md files)
if (options.ignorePaths) {
if (!Array.isArray(options.ignorePaths)) {
throw new Error('options.ignorePaths must be an array');
}
if (options.ignorePaths.some(ignorePath => ignorePath === relativeFilePath)) {
// Skip copying this file
return;
}
}
let contentChangedCallback = null;
if (options.upgrade && !options.force) {
contentChangedCallback = (_destPath, contentChanged) => upgradeFileContentChangedCallback(absoluteSrcFilePath, relativeFilePath, contentChanged);
}
(0, _copyAndReplace.default)(absoluteSrcFilePath, _path().default.resolve(destPath, relativeFilePath), {
'Hello App Display Name': options.displayName || newProjectName,
HelloWorld: newProjectName,
helloworld: newProjectName.toLowerCase()
}, contentChangedCallback);
});
}
/**
* There are various files in the templates folder in the RN repo. We want
* these to be ignored by tools when working with React Native itself.
* Example: _babelrc file is ignored by Babel, renamed to .babelrc inside
* a real app folder.
* This is especially important for .gitignore because npm has some special
* behavior of automatically renaming .gitignore to .npmignore.
*/
function translateFilePath(filePath) {
if (!filePath) {
return filePath;
}
return filePath.replace('_BUCK', 'BUCK').replace('_gitignore', '.gitignore').replace('_gitattributes', '.gitattributes').replace('_babelrc', '.babelrc').replace('_eslintrc.js', '.eslintrc.js').replace('_flowconfig', '.flowconfig').replace('_buckconfig', '.buckconfig').replace('_prettierrc.js', '.prettierrc.js').replace('_watchmanconfig', '.watchmanconfig');
}
function upgradeFileContentChangedCallback(absoluteSrcFilePath, relativeDestPath, contentChanged) {
if (contentChanged === 'new') {
_cliTools().logger.info(`${_chalk().default.bold('new')} ${relativeDestPath}`);
return 'overwrite';
}
if (contentChanged === 'changed') {
_cliTools().logger.info(`${_chalk().default.bold(relativeDestPath)} ` + `has changed in the new version.\nDo you want to keep your ${relativeDestPath} or replace it with the ` + 'latest version?\nIf you ever made any changes ' + "to this file, you'll probably want to keep it.\n" + `You can see the new version here: ${absoluteSrcFilePath}\n` + `Do you want to replace ${relativeDestPath}? ` + 'Answer y to replace, n to keep your version: ');
const answer = prompt();
if (answer === 'y') {
_cliTools().logger.info(`Replacing ${relativeDestPath}`);
return 'overwrite';
}
_cliTools().logger.info(`Keeping your ${relativeDestPath}`);
return 'keep';
}
if (contentChanged === 'identical') {
return 'keep';
}
throw new Error(`Unknown file changed state: ${relativeDestPath}, ${contentChanged}`);
}
var _default = copyProjectTemplateAndReplace;
exports.default = _default;
//# sourceMappingURL=copyProjectTemplateAndReplace.js.map

View File

@ -0,0 +1,164 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _fs() {
const data = _interopRequireDefault(require("fs"));
_fs = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
// Simplified version of:
// https://github.com/0x00A/prompt-sync/blob/master/index.js
const term = 13; // carriage return
function create() {
return prompt;
function prompt(ask, value, opts) {
let insert = 0;
opts = opts || {};
if (typeof ask === 'object') {
opts = ask;
ask = opts.ask;
} else if (typeof value === 'object') {
opts = value;
value = opts.value;
}
ask = ask || '';
const echo = opts.echo;
const masked = ('echo' in opts);
let fd;
if (process.platform === 'win32') {
// @ts-ignore
fd = process.stdin.fd;
} else {
fd = _fs().default.openSync('/dev/tty', 'rs');
}
const wasRaw = process.stdin.isRaw;
if (!wasRaw && process.stdin.setRawMode) {
process.stdin.setRawMode(true);
}
let buf = Buffer.alloc(3);
let str = '';
let character;
let read;
if (ask) {
process.stdout.write(ask);
}
while (true) {
read = _fs().default.readSync(fd, buf, 0, 3, null);
if (read > 1) {
// received a control sequence
if (buf.toString()) {
str += buf.toString();
str = str.replace(/\0/g, '');
insert = str.length;
process.stdout.write(`\u001b[2K\u001b[0G${ask}${str}`);
process.stdout.write(`\u001b[${insert + ask.length + 1}G`);
buf = Buffer.alloc(3);
}
continue; // any other 3 character sequence is ignored
} // if it is not a control character seq, assume only one character is read
character = buf[read - 1]; // catch a ^C and return null
if (character === 3) {
process.stdout.write('^C\n');
_fs().default.closeSync(fd);
process.exit(130);
if (process.stdin.setRawMode) {
process.stdin.setRawMode(!!wasRaw);
}
return null;
} // catch the terminating character
if (character === term) {
_fs().default.closeSync(fd);
break;
}
if (character === 127 || process.platform === 'win32' && character === 8) {
// backspace
if (!insert) {
continue;
}
str = str.slice(0, insert - 1) + str.slice(insert);
insert--;
process.stdout.write('\u001b[2D');
} else {
if (character < 32 || character > 126) {
continue;
}
str = str.slice(0, insert) + String.fromCharCode(character) + str.slice(insert);
insert++;
}
if (masked) {
process.stdout.write(`\u001b[2K\u001b[0G${ask}${Array(str.length + 1).join(echo)}`);
} else {
process.stdout.write('\u001b[s');
if (insert === str.length) {
process.stdout.write(`\u001b[2K\u001b[0G${ask}${str}`);
} else if (ask) {
process.stdout.write(`\u001b[2K\u001b[0G${ask}${str}`);
} else {
process.stdout.write(`\u001b[2K\u001b[0G${str}\u001b[${str.length - insert}D`);
}
process.stdout.write('\u001b[u');
process.stdout.write('\u001b[1C');
}
}
process.stdout.write('\n');
if (process.stdin.setRawMode) {
process.stdin.setRawMode(!!wasRaw);
}
return str || value || '';
}
}
var _default = create;
exports.default = _default;
//# sourceMappingURL=promptSync.js.map

View File

@ -0,0 +1,205 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createProjectFromTemplate = createProjectFromTemplate;
function _child_process() {
const data = require("child_process");
_child_process = function () {
return data;
};
return data;
}
function _fs() {
const data = _interopRequireDefault(require("fs"));
_fs = function () {
return data;
};
return data;
}
function _path() {
const data = _interopRequireDefault(require("path"));
_path = function () {
return data;
};
return data;
}
var _copyProjectTemplateAndReplace = _interopRequireDefault(require("./copyProjectTemplateAndReplace"));
function _cliTools() {
const data = require("@react-native-community/cli-tools");
_cliTools = function () {
return data;
};
return data;
}
var PackageManager = _interopRequireWildcard(require("../packageManager"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @param destPath Create the new project at this path.
* @param newProjectName For example 'AwesomeApp'.
* @param template Template to use, for example 'navigation'.
*/
async function createProjectFromTemplate(destPath, newProjectName, template) {
const templatePath = _path().default.dirname(require.resolve('react-native/template'));
(0, _copyProjectTemplateAndReplace.default)(templatePath, destPath, newProjectName);
if (template === undefined) {
// No specific template, use just the react-native template above
return;
} // Keep the files from the react-native template, and overwrite some of them
// with the specified project template.
// The react-native template contains the native files (these are used by
// all templates) and every other template only contains additional JS code.
// Reason:
// This way we don't have to duplicate the native files in every template.
// If we duplicated them we'd make RN larger and risk that people would
// forget to maintain all the copies so they would go out of sync.
await createFromRemoteTemplate(template, destPath, newProjectName);
}
/**
* The following formats are supported for the template:
* - 'demo' -> Fetch the package react-native-template-demo from npm
* - git://..., http://..., file://... or any other URL supported by npm
*/
async function createFromRemoteTemplate(template, destPath, newProjectName) {
let installPackage;
let templateName;
if (template.includes(':/')) {
// URL, e.g. git://, file://, file:/
installPackage = template;
templateName = template.substr(template.lastIndexOf('/') + 1);
} else {
// e.g 'demo'
installPackage = `react-native-template-${template}`;
templateName = installPackage;
} // Check if the template exists
_cliTools().logger.info(`Fetching template ${installPackage}...`);
try {
await PackageManager.install([installPackage], {
root: destPath
});
const templatePath = _path().default.resolve('node_modules', templateName);
(0, _copyProjectTemplateAndReplace.default)(templatePath, destPath, newProjectName, {
// Every template contains a dummy package.json file included
// only for publishing the template to npm.
// We want to ignore this dummy file, otherwise it would overwrite
// our project's package.json file.
ignorePaths: ['package.json', 'dependencies.json', 'devDependencies.json']
});
await installTemplateDependencies(templatePath, destPath);
await installTemplateDevDependencies(templatePath, destPath);
} finally {
// Clean up the temp files
try {
await PackageManager.uninstall([templateName], {
root: destPath
});
} catch (err) {
// Not critical but we still want people to know and report
// if this the clean up fails.
_cliTools().logger.warn(`Failed to clean up template temp files in node_modules/${templateName}. ` + 'This is not a critical error, you can work on your app.');
}
}
}
async function installTemplateDependencies(templatePath, root) {
// dependencies.json is a special file that lists additional dependencies
// that are required by this template
const dependenciesJsonPath = _path().default.resolve(templatePath, 'dependencies.json');
_cliTools().logger.info('Adding dependencies for the project...');
if (!_fs().default.existsSync(dependenciesJsonPath)) {
_cliTools().logger.info('No additional dependencies.');
return;
}
let dependencies;
try {
dependencies = require(dependenciesJsonPath);
} catch (err) {
throw new Error(`Could not parse the template's dependencies.json: ${err.message}`);
}
const dependenciesToInstall = Object.keys(dependencies).map(depName => `${depName}@${dependencies[depName]}`);
await PackageManager.install(dependenciesToInstall, {
root
});
_cliTools().logger.info("Linking native dependencies into the project's build files...");
(0, _child_process().execSync)('react-native link', {
cwd: root,
stdio: 'inherit'
});
}
async function installTemplateDevDependencies(templatePath, root) {
// devDependencies.json is a special file that lists additional develop dependencies
// that are required by this template
const devDependenciesJsonPath = _path().default.resolve(templatePath, 'devDependencies.json');
_cliTools().logger.info('Adding develop dependencies for the project...');
if (!_fs().default.existsSync(devDependenciesJsonPath)) {
_cliTools().logger.info('No additional develop dependencies.');
return;
}
let dependencies;
try {
dependencies = require(devDependenciesJsonPath);
} catch (err) {
throw new Error(`Could not parse the template's devDependencies.json: ${err.message}`);
}
const dependenciesToInstall = Object.keys(dependencies).map(depName => `${depName}@${dependencies[depName]}`);
await PackageManager.installDev(dependenciesToInstall, {
root
});
}
//# sourceMappingURL=templates.js.map