Prettier RN local-cli

Reviewed By: yungsters

Differential Revision: D7962462

fbshipit-source-id: 0afe2092af8703895de91a6d1400315c3173aa6d
This commit is contained in:
Eli White 2018-05-11 12:43:49 -07:00 committed by Facebook Github Bot
parent 680fb50040
commit aba4ec0c09
209 changed files with 3167 additions and 2071 deletions

View File

@ -3,10 +3,13 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
'use strict';
// beeper@1.1.0 has a return statement outside of a function
// and therefore doesn't parse. Let's mock it so that we can
// run the tests.
module.exports = function () {};
module.exports = function() {};

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
function sign(source) {

View File

@ -4,19 +4,23 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
'use strict';
jest
.dontMock('../filterPlatformAssetScales')
.dontMock('../assetPathUtils');
jest.dontMock('../filterPlatformAssetScales').dontMock('../assetPathUtils');
const filterPlatformAssetScales = require('../filterPlatformAssetScales');
describe('filterPlatformAssetScales', () => {
it('removes everything but 2x and 3x for iOS', () => {
expect(filterPlatformAssetScales('ios', [1, 1.5, 2, 3, 4])).toEqual([1, 2, 3]);
expect(filterPlatformAssetScales('ios', [1, 1.5, 2, 3, 4])).toEqual([
1,
2,
3,
]);
expect(filterPlatformAssetScales('ios', [3, 4])).toEqual([3]);
});
@ -28,6 +32,11 @@ describe('filterPlatformAssetScales', () => {
});
it('keeps all scales for unknown platform', () => {
expect(filterPlatformAssetScales('freebsd', [1, 1.5, 2, 3.7])).toEqual([1, 1.5, 2, 3.7]);
expect(filterPlatformAssetScales('freebsd', [1, 1.5, 2, 3.7])).toEqual([
1,
1.5,
2,
3.7,
]);
});
});

View File

@ -4,13 +4,13 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
'use strict';
jest
.dontMock('../getAssetDestPathAndroid')
.dontMock('../assetPathUtils');
jest.dontMock('../getAssetDestPathAndroid').dontMock('../assetPathUtils');
const getAssetDestPathAndroid = require('../getAssetDestPathAndroid');
@ -24,7 +24,9 @@ describe('getAssetDestPathAndroid', () => {
const expectDestPathForScaleToStartWith = (scale, path) => {
if (!getAssetDestPathAndroid(asset, scale).startsWith(path)) {
throw new Error(`asset for scale ${scale} should start with path '${path}'`);
throw new Error(
`asset for scale ${scale} should start with path '${path}'`,
);
}
};
@ -43,7 +45,7 @@ describe('getAssetDestPathAndroid', () => {
};
expect(getAssetDestPathAndroid(asset, 1)).toBe(
'drawable-mdpi/app_test_icon.png'
'drawable-mdpi/app_test_icon.png',
);
});
@ -54,9 +56,7 @@ describe('getAssetDestPathAndroid', () => {
httpServerLocation: '/assets/RKJSModules/Apps/AndroidSample/Assets',
};
expect(
getAssetDestPathAndroid(asset, 1).startsWith('assets_')
).toBeFalsy();
expect(getAssetDestPathAndroid(asset, 1).startsWith('assets_')).toBeFalsy();
});
it('should put non-drawable resources to `raw/`', () => {
@ -66,8 +66,6 @@ describe('getAssetDestPathAndroid', () => {
httpServerLocation: '/assets/app/test',
};
expect(getAssetDestPathAndroid(asset, 1)).toBe(
'raw/app_test_video.mp4'
);
expect(getAssetDestPathAndroid(asset, 1)).toBe('raw/app_test_video.mp4');
});
});

View File

@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
'use strict';
jest.dontMock('../getAssetDestPathIOS');

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
@ -17,12 +18,18 @@ import type {PackagerAsset} from '../../Libraries/Image/AssetRegistry';
*/
function getAndroidAssetSuffix(scale: number): string {
switch (scale) {
case 0.75: return 'ldpi';
case 1: return 'mdpi';
case 1.5: return 'hdpi';
case 2: return 'xhdpi';
case 3: return 'xxhdpi';
case 4: return 'xxxhdpi';
case 0.75:
return 'ldpi';
case 1:
return 'mdpi';
case 1.5:
return 'hdpi';
case 2:
return 'xhdpi';
case 3:
return 'xxhdpi';
case 4:
return 'xxxhdpi';
}
throw new Error('no such scale');
}
@ -45,8 +52,8 @@ function getAndroidResourceFolderName(asset: PackagerAsset, scale: number) {
var suffix = getAndroidAssetSuffix(scale);
if (!suffix) {
throw new Error(
'Don\'t know which android drawable suffix to use for asset: ' +
JSON.stringify(asset)
"Don't know which android drawable suffix to use for asset: " +
JSON.stringify(asset),
);
}
const androidFolder = 'drawable-' + suffix;
@ -74,5 +81,5 @@ module.exports = {
getAndroidAssetSuffix: getAndroidAssetSuffix,
getAndroidResourceFolderName: getAndroidResourceFolderName,
getAndroidResourceIdentifier: getAndroidResourceIdentifier,
getBasePath: getBasePath
getBasePath: getBasePath,
};

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
@ -117,11 +118,7 @@ async function buildBundle(
});
// When we're done saving bundle output and the assets, we're done.
const assets = await saveAssets(
outputAssets,
args.platform,
args.assetsDest,
);
const assets = await saveAssets(outputAssets, args.platform, args.assetsDest);
server.end();

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const buildBundle = require('./buildBundle');

View File

@ -3,68 +3,94 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
module.exports = [
{
command: '--entry-file <path>',
description: 'Path to the root JS file, either absolute or relative to JS root',
}, {
description:
'Path to the root JS file, either absolute or relative to JS root',
},
{
command: '--platform [string]',
description: 'Either "ios" or "android"',
default: 'ios',
}, {
},
{
command: '--transformer [string]',
description: 'Specify a custom transformer to be used',
}, {
},
{
command: '--dev [boolean]',
description: 'If false, warnings are disabled and the bundle is minified',
parse: (val) => val === 'false' ? false : true,
parse: val => (val === 'false' ? false : true),
default: true,
}, {
},
{
command: '--minify [boolean]',
description: 'Allows overriding whether bundle is minified. This defaults to ' +
description:
'Allows overriding whether bundle is minified. This defaults to ' +
'false if dev is true, and true if dev is false. Disabling minification ' +
'can be useful for speeding up production builds for testing purposes.',
parse: (val) => val === 'false' ? false : true,
}, {
parse: val => (val === 'false' ? false : true),
},
{
command: '--bundle-output <string>',
description: 'File name where to store the resulting bundle, ex. /tmp/groups.bundle',
}, {
description:
'File name where to store the resulting bundle, ex. /tmp/groups.bundle',
},
{
command: '--bundle-encoding [string]',
description: 'Encoding the bundle should be written in (https://nodejs.org/api/buffer.html#buffer_buffer).',
description:
'Encoding the bundle should be written in (https://nodejs.org/api/buffer.html#buffer_buffer).',
default: 'utf8',
}, {
},
{
command: '--max-workers [number]',
description: 'Specifies the maximum number of workers the worker-pool ' +
description:
'Specifies the maximum number of workers the worker-pool ' +
'will spawn for transforming files. This defaults to the number of the ' +
'cores available on your machine.',
parse: (workers: string) => Number(workers),
}, {
},
{
command: '--sourcemap-output [string]',
description: 'File name where to store the sourcemap file for resulting bundle, ex. /tmp/groups.map',
}, {
description:
'File name where to store the sourcemap file for resulting bundle, ex. /tmp/groups.map',
},
{
command: '--sourcemap-sources-root [string]',
description: 'Path to make sourcemap\'s sources entries relative to, ex. /root/dir',
}, {
description:
"Path to make sourcemap's sources entries relative to, ex. /root/dir",
},
{
command: '--sourcemap-use-absolute-path',
description: 'Report SourceMapURL using its full path',
default: false,
}, {
},
{
command: '--assets-dest [string]',
description: 'Directory name where to store assets referenced in the bundle',
}, {
description:
'Directory name where to store assets referenced in the bundle',
},
{
command: '--verbose',
description: 'Enables logging',
default: false,
}, {
},
{
command: '--reset-cache',
description: 'Removes cached files',
default: false,
}, {
},
{
command: '--read-global-cache',
description: 'Try to fetch transformed JS code from the global cache, if configured.',
description:
'Try to fetch transformed JS code from the global cache, if configured.',
default: false,
},
];

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
@ -15,7 +16,10 @@ const path = require('path');
import type {PackagerAsset} from '../../Libraries/Image/AssetRegistry';
function getAssetDestPathAndroid(asset: PackagerAsset, scale: number): string {
const androidFolder = assetPathUtils.getAndroidResourceFolderName(asset, scale);
const androidFolder = assetPathUtils.getAndroidResourceFolderName(
asset,
scale,
);
const fileName = assetPathUtils.getAndroidResourceIdentifier(asset);
return path.join(androidFolder, fileName + '.' + asset.type);
}

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const filterPlatformAssetScales = require('./filterPlatformAssetScales');
@ -14,24 +17,20 @@ const log = require('../util/log').out('bundle');
const mkdirp = require('mkdirp');
const path = require('path');
function saveAssets(
assets,
platform,
assetsDest
) {
function saveAssets(assets, platform, assetsDest) {
if (!assetsDest) {
console.warn('Assets destination folder is not set, skipping...');
return Promise.resolve();
}
const getAssetDestPath = platform === 'android'
? getAssetDestPathAndroid
: getAssetDestPathIOS;
const getAssetDestPath =
platform === 'android' ? getAssetDestPathAndroid : getAssetDestPathIOS;
const filesToCopy = Object.create(null); // Map src -> dest
assets
.forEach(asset => {
const validScales = new Set(filterPlatformAssetScales(platform, asset.scales));
assets.forEach(asset => {
const validScales = new Set(
filterPlatformAssetScales(platform, asset.scales),
);
asset.scales.forEach((scale, idx) => {
if (!validScales.has(scale)) {
return;
@ -53,7 +52,7 @@ function copyAll(filesToCopy) {
log('Copying ' + queue.length + ' asset files');
return new Promise((resolve, reject) => {
const copyNext = (error) => {
const copyNext = error => {
if (error) {
return reject(error);
}
@ -76,7 +75,8 @@ function copy(src, dest, callback) {
if (err) {
return callback(err);
}
fs.createReadStream(src)
fs
.createReadStream(src)
.pipe(fs.createWriteStream(dest))
.on('finish', callback);
});

View File

@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
/* $FlowFixMe(site=react_native_oss) */

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const bundleWithOutput = require('./bundle').withOutput;
@ -23,7 +26,8 @@ module.exports = {
func: unbundle,
options: bundleCommandLineArgs.concat({
command: '--indexed-unbundle',
description: 'Force indexed unbundle file format, even when building for android',
description:
'Force indexed unbundle file format, even when building for android',
default: false,
}),
};

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
// gracefulify() has to be called before anything else runs

View File

@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const config = require('./core');
@ -30,9 +32,9 @@ import type {RNConfig} from './core';
commander.version(pkg.version);
const defaultOptParser = (val) => val;
const defaultOptParser = val => val;
const handleError = (err) => {
const handleError = err => {
console.error();
console.error(err.message || err);
console.error();
@ -48,15 +50,12 @@ function printHelpInformation() {
}
const sourceInformation = this.pkg
? [
` ${chalk.bold('Source:')} ${this.pkg.name}@${this.pkg.version}`,
'',
]
? [` ${chalk.bold('Source:')} ${this.pkg.name}@${this.pkg.version}`, '']
: [];
let output = [
'',
chalk.bold(chalk.cyan((` react-native ${cmdName} ${this.usage()}`))),
chalk.bold(chalk.cyan(` react-native ${cmdName} ${this.usage()}`)),
` ${this._description}`,
'',
...sourceInformation,
@ -67,9 +66,9 @@ function printHelpInformation() {
];
if (this.examples && this.examples.length > 0) {
const formattedUsage = this.examples.map(
example => ` ${example.desc}: \n ${chalk.cyan(example.cmd)}`,
).join('\n\n');
const formattedUsage = this.examples
.map(example => ` ${example.desc}: \n ${chalk.cyan(example.cmd)}`)
.join('\n\n');
output = output.concat([
chalk.bold(' Example usage:'),
@ -78,21 +77,22 @@ function printHelpInformation() {
]);
}
return output.concat([
'',
'',
]).join('\n');
return output.concat(['', '']).join('\n');
}
function printUnknownCommand(cmdName) {
console.log([
console.log(
[
'',
cmdName
? chalk.red(` Unrecognized command '${cmdName}'`)
: chalk.red(' You didn\'t pass any command'),
` Run ${chalk.cyan('react-native --help')} to see list of all available commands`,
: chalk.red(" You didn't pass any command"),
` Run ${chalk.cyan(
'react-native --help',
)} to see list of all available commands`,
'',
].join('\n'));
].join('\n'),
);
}
const addCommand = (command: CommandT, cfg: RNConfig) => {
@ -119,13 +119,14 @@ const addCommand = (command: CommandT, cfg: RNConfig) => {
cmd.examples = command.examples;
cmd.pkg = command.pkg;
options
.forEach(opt => cmd.option(
options.forEach(opt =>
cmd.option(
opt.command,
opt.description,
opt.parse || defaultOptParser,
typeof opt.default === 'function' ? opt.default(cfg) : opt.default,
));
),
);
// Placeholder option for --config, which is parsed before any other option,
// but needs to be here to avoid "unknown option" errors when specified
@ -143,7 +144,9 @@ function run() {
commander.parse(process.argv);
const isValidCommand = commands.find(cmd => cmd.name.split(' ')[0] === process.argv[2]);
const isValidCommand = commands.find(
cmd => cmd.name.split(' ')[0] === process.argv[2],
);
if (!isValidCommand) {
printUnknownCommand(process.argv[2]);

View File

@ -4,13 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const { getProjectCommands } = require('./core');
const {getProjectCommands} = require('./core');
import type { RNConfig } from './core';
import type {RNConfig} from './core';
export type CommandT = {
name: string,
@ -58,10 +60,12 @@ const undocumentedCommands = [
{
name: 'init',
func: () => {
console.log([
console.log(
[
'Looks like React Native project already exists in the current',
'folder. Run this command from a different folder or remove node_modules/react-native',
].join('\n'));
].join('\n'),
);
},
},
];

View File

@ -1,8 +1,14 @@
/** @format */
const fs = require.requireActual('fs');
const path = require('path');
const manifest = fs.readFileSync(path.join(__dirname, './files/AndroidManifest.xml'));
const mainJavaClass = fs.readFileSync(path.join(__dirname, './files/Main.java'));
const manifest = fs.readFileSync(
path.join(__dirname, './files/AndroidManifest.xml'),
);
const mainJavaClass = fs.readFileSync(
path.join(__dirname, './files/Main.java'),
);
function generateValidFileStructure(classFileName) {
return {
@ -13,7 +19,9 @@ function generateValidFileStructure(classFileName) {
some: {
example: {
'Main.java': mainJavaClass,
[classFileName]: fs.readFileSync(path.join(__dirname, `./files/${classFileName}`)),
[classFileName]: fs.readFileSync(
path.join(__dirname, `./files/${classFileName}`),
),
},
},
},
@ -34,13 +42,17 @@ exports.userConfigManifest = {
some: {
example: {
'Main.java': mainJavaClass,
'ReactPackage.java': fs.readFileSync(path.join(__dirname, './files/ReactPackage.java')),
'ReactPackage.java': fs.readFileSync(
path.join(__dirname, './files/ReactPackage.java'),
),
},
},
},
},
debug: {
'AndroidManifest.xml': fs.readFileSync(path.join(__dirname, './files/AndroidManifest-debug.xml')),
'AndroidManifest.xml': fs.readFileSync(
path.join(__dirname, './files/AndroidManifest-debug.xml'),
),
},
},
};

View File

@ -1,15 +1,20 @@
/** @format */
exports.single = {
func: () => {},
description: 'Test action',
name: 'test',
};
exports.multiple = [{
exports.multiple = [
{
func: () => {},
description: 'Test action #1',
name: 'test1',
}, {
},
{
func: () => {},
description: 'Test action #2',
name: 'test2',
}];
},
];

View File

@ -1,3 +1,5 @@
/** @format */
const fs = require.requireActual('fs');
const path = require('path');
const android = require('./android');

View File

@ -1,19 +1,25 @@
/** @format */
const fs = require.requireActual('fs');
const path = require('path');
exports.valid = {
'demoProject.xcodeproj': {
'project.pbxproj': fs.readFileSync(path.join(__dirname, './files/project.pbxproj')),
'project.pbxproj': fs.readFileSync(
path.join(__dirname, './files/project.pbxproj'),
),
},
'TestPod.podspec': 'empty'
'TestPod.podspec': 'empty',
};
exports.validTestName = {
'MyTestProject.xcodeproj': {
'project.pbxproj': fs.readFileSync(path.join(__dirname, './files/project.pbxproj')),
'project.pbxproj': fs.readFileSync(
path.join(__dirname, './files/project.pbxproj'),
),
},
};
exports.pod = {
'TestPod.podspec': 'empty'
'TestPod.podspec': 'empty',
};

View File

@ -1,10 +1,12 @@
/** @format */
const android = require('./android');
const ios = require('./ios');
const flat = {
android: android.valid,
ios: ios.valid,
Podfile: 'empty'
Podfile: 'empty',
};
const nested = {
@ -22,7 +24,7 @@ const withExamples = {
const withPods = {
Podfile: 'content',
ios: ios.pod
ios: ios.pod,
};
module.exports = { flat, nested, withExamples, withPods };
module.exports = {flat, nested, withExamples, withPods};

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -32,9 +33,9 @@ describe('ios::findPodspecName', () => {
user: {
PacketName: {
'Another.podspec': 'empty',
'PacketName.podspec': 'empty'
}
}
'PacketName.podspec': 'empty',
},
},
});
expect(findPodspecName('/user/PacketName')).toBe('PacketName');
});
@ -44,9 +45,9 @@ describe('ios::findPodspecName', () => {
user: {
packet: {
'Another.podspec': 'empty',
'PacketName.podspec': 'empty'
}
}
'PacketName.podspec': 'empty',
},
},
});
expect(findPodspecName('/user/packet')).toBe('Another');
});

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const fs = require('fs');

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const glob = require('glob');

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const fs = require('fs');
@ -17,7 +20,7 @@ const path = require('path');
* @param {String} folder Folder to find java/kt files
*/
module.exports = function getPackageClassName(folder) {
const files = glob.sync('**/+(*.java|*.kt)', { cwd: folder });
const files = glob.sync('**/+(*.java|*.kt)', {cwd: folder});
const packages = files
.map(filePath => fs.readFileSync(path.join(folder, filePath), 'utf8'))

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const findAndroidAppFolder = require('./findAndroidAppFolder');
@ -12,7 +15,7 @@ const findPackageClassName = require('./findPackageClassName');
const path = require('path');
const readManifest = require('./readManifest');
const getPackageName = (manifest) => manifest.attr.package;
const getPackageName = manifest => manifest.attr.package;
/**
* Gets android project config by analyzing given folder and taking some
@ -43,33 +46,34 @@ exports.projectConfig = function projectConfigAndroid(folder, userConfig) {
throw new Error(`Package name not found in ${manifestPath}`);
}
const packageFolder = userConfig.packageFolder ||
packageName.replace(/\./g, path.sep);
const packageFolder =
userConfig.packageFolder || packageName.replace(/\./g, path.sep);
const mainFilePath = path.join(
sourceDir,
userConfig.mainFilePath || `src/main/java/${packageFolder}/MainApplication.java`
userConfig.mainFilePath ||
`src/main/java/${packageFolder}/MainApplication.java`,
);
const stringsPath = path.join(
sourceDir,
userConfig.stringsPath || 'src/main/res/values/strings.xml'
userConfig.stringsPath || 'src/main/res/values/strings.xml',
);
const settingsGradlePath = path.join(
folder,
'android',
userConfig.settingsGradlePath || 'settings.gradle'
userConfig.settingsGradlePath || 'settings.gradle',
);
const assetsPath = path.join(
sourceDir,
userConfig.assetsPath || 'src/main/assets'
userConfig.assetsPath || 'src/main/assets',
);
const buildGradlePath = path.join(
sourceDir,
userConfig.buildGradlePath || 'build.gradle'
userConfig.buildGradlePath || 'build.gradle',
);
return {
@ -89,7 +93,10 @@ exports.projectConfig = function projectConfigAndroid(folder, userConfig) {
* Same as projectConfigAndroid except it returns
* different config that applies to packages only
*/
exports.dependencyConfig = function dependencyConfigAndroid(folder, userConfig) {
exports.dependencyConfig = function dependencyConfigAndroid(
folder,
userConfig,
) {
const src = userConfig.sourceDir || findAndroidAppFolder(folder);
if (!src) {
@ -116,13 +123,14 @@ exports.dependencyConfig = function dependencyConfigAndroid(folder, userConfig)
return null;
}
const packageImportPath = userConfig.packageImportPath ||
const packageImportPath =
userConfig.packageImportPath ||
`import ${packageName}.${packageClassName};`;
const packageInstance = userConfig.packageInstance ||
`new ${packageClassName}()`;
const packageInstance =
userConfig.packageInstance || `new ${packageClassName}()`;
return { sourceDir, folder, manifest, packageImportPath, packageInstance };
return {sourceDir, folder, manifest, packageImportPath, packageInstance};
};
exports.linkConfig = require('../../link/android');

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const fs = require('fs');

View File

@ -3,14 +3,17 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const glob = require('glob');
const path = require('path');
const findAssetsInFolder = (folder) =>
glob.sync(path.join(folder, '**'), { nodir: true });
const findAssetsInFolder = folder =>
glob.sync(path.join(folder, '**'), {nodir: true});
/**
* Given an array of assets folders, e.g. ['Fonts', 'Images'],
@ -21,8 +24,9 @@ const findAssetsInFolder = (folder) =>
module.exports = function findAssets(folder, assets) {
return (assets || [])
.map(assetsFolder => path.join(folder, assetsFolder))
.reduce((_assets, assetsFolder) =>
.reduce(
(_assets, assetsFolder) =>
_assets.concat(findAssetsInFolder(assetsFolder)),
[]
[],
);
};

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const path = require('path');
@ -16,10 +19,11 @@ const flatten = require('lodash').flatten;
* @param {String} dependency Name of the dependency
* @return {Boolean} If dependency is a rnpm plugin
*/
const isRNPMPlugin = (dependency) => dependency.indexOf('rnpm-plugin-') === 0;
const isReactNativePlugin = (dependency) => dependency.indexOf('react-native-') === 0;
const isRNPMPlugin = dependency => dependency.indexOf('rnpm-plugin-') === 0;
const isReactNativePlugin = dependency =>
dependency.indexOf('react-native-') === 0;
const readPackage = (folder) => {
const readPackage = folder => {
try {
return require(path.join(folder, 'package.json'));
} catch (e) {
@ -27,7 +31,7 @@ const readPackage = (folder) => {
}
};
const findPluginsInReactNativePackage = (pjson) => {
const findPluginsInReactNativePackage = pjson => {
if (!pjson.rnpm || !pjson.rnpm.plugin) {
return [];
}
@ -35,7 +39,7 @@ const findPluginsInReactNativePackage = (pjson) => {
return path.join(pjson.name, pjson.rnpm.plugin);
};
const findPlatformsInPackage = (pjson) => {
const findPlatformsInPackage = pjson => {
if (!pjson.rnpm || !pjson.rnpm.platform) {
return [];
}
@ -43,7 +47,7 @@ const findPlatformsInPackage = (pjson) => {
return path.join(pjson.name, pjson.rnpm.platform);
};
const findPluginInFolder = (folder) => {
const findPluginInFolder = folder => {
const pjson = readPackage(folder);
if (!pjson) {
@ -52,7 +56,7 @@ const findPluginInFolder = (folder) => {
const deps = union(
Object.keys(pjson.dependencies || {}),
Object.keys(pjson.devDependencies || {})
Object.keys(pjson.devDependencies || {}),
);
return deps.reduce(
@ -71,7 +75,7 @@ const findPluginInFolder = (folder) => {
}
return {commands: commands, platforms: platforms};
},
{commands: [], platforms: []}
{commands: [], platforms: []},
);
};
@ -84,6 +88,6 @@ module.exports = function findPlugins(folders) {
const plugins = folders.map(findPluginInFolder);
return {
commands: uniq(flatten(plugins.map(p => p.commands))),
platforms: uniq(flatten(plugins.map(p => p.platforms)))
platforms: uniq(flatten(plugins.map(p => p.platforms))),
};
};

View File

@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const android = require('./android');
@ -48,37 +50,35 @@ export type RNConfig = {
getDependencyConfig(pkgName: string): Object,
};
const getRNPMConfig = (folder) =>
const getRNPMConfig = folder =>
// $FlowFixMe non-literal require
require(path.join(folder, './package.json')).rnpm || {};
const attachPackage = (command, pkg) => Array.isArray(command)
const attachPackage = (command, pkg) =>
Array.isArray(command)
? command.map(cmd => attachPackage(cmd, pkg))
: { ...command, pkg };
: {...command, pkg};
const appRoot = process.cwd();
const plugins = findPlugins([appRoot]);
const pluginPlatforms = plugins
.platforms
.reduce((acc, pathToPlatforms) => {
const pluginPlatforms = plugins.platforms.reduce((acc, pathToPlatforms) => {
return Object.assign(
acc,
// $FlowFixMe non-literal require
return Object.assign(acc, require(path.join(appRoot, 'node_modules', pathToPlatforms)));
},
{});
require(path.join(appRoot, 'node_modules', pathToPlatforms)),
);
}, {});
const defaultRNConfig = {
hasteImplModulePath: require.resolve('../../jest/hasteImpl'),
getProjectCommands(): Array<CommandT> {
const commands = plugins
.commands
.map(pathToCommands => {
const commands = plugins.commands.map(pathToCommands => {
const name = pathToCommands.split(path.sep)[0];
return attachPackage(
require(path.join(appRoot, 'node_modules', pathToCommands)),
require(path.join(appRoot, 'node_modules', name, 'package.json'))
require(path.join(appRoot, 'node_modules', name, 'package.json')),
);
});
@ -89,7 +89,7 @@ const defaultRNConfig = {
return {
ios,
android,
...pluginPlatforms
...pluginPlatforms,
};
},
@ -113,7 +113,7 @@ const defaultRNConfig = {
const platforms = this.getPlatformConfig();
const folder = path.join(process.cwd(), 'node_modules', packageName);
const rnpm = getRNPMConfig(
path.join(process.cwd(), 'node_modules', packageName)
path.join(process.cwd(), 'node_modules', packageName),
);
let config = Object.assign({}, rnpm, {
@ -135,7 +135,8 @@ const defaultRNConfig = {
*/
function getCliConfig(): RNConfig {
const cliArgs = minimist(process.argv.slice(2));
const config = cliArgs.config != null
const config =
cliArgs.config != null
? Config.load(path.resolve(__dirname, cliArgs.config))
: Config.findOptional(__dirname);

View File

@ -1,3 +1,5 @@
/** @format */
'use strict';
const fs = require('fs');

View File

@ -1,25 +1,24 @@
/** @format */
'use strict';
const glob = require('glob');
const path = require('path');
module.exports = function findPodspecName(folder) {
const podspecs = glob.sync('*.podspec', { cwd: folder });
const podspecs = glob.sync('*.podspec', {cwd: folder});
let podspecFile = null;
if (podspecs.length === 0) {
return null;
}
else if (podspecs.length === 1) {
} else if (podspecs.length === 1) {
podspecFile = podspecs[0];
}
else {
} else {
const folderParts = folder.split(path.sep);
const currentFolder = folderParts[folderParts.length - 1];
const toSelect = podspecs.indexOf(currentFolder + '.podspec');
if (toSelect === -1) {
podspecFile = podspecs[0];
}
else {
} else {
podspecFile = podspecs[toSelect];
}
}

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const glob = require('glob');

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const findProject = require('./findProject');
@ -15,7 +18,7 @@ const path = require('path');
* For libraries specified without an extension, add '.tbd' for those that
* start with 'lib' and '.framework' to the rest.
*/
const mapSharedLibaries = (libraries) => {
const mapSharedLibaries = libraries => {
return libraries.map(name => {
if (path.extname(name)) {
return name;

View File

@ -3,15 +3,20 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const spawn = require('child_process').spawn;
module.exports = function makeCommand(command) {
return (cb) => {
return cb => {
if (!cb) {
throw new Error(`You missed a callback function for the ${command} command`);
throw new Error(
`You missed a callback function for the ${command} command`,
);
}
const args = command.split(' ');

View File

@ -3,14 +3,17 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const makeCommand = require('./makeCommand');
module.exports = function wrapCommands(commands) {
const mappedCommands = {};
Object.keys(commands || []).forEach((k) => {
Object.keys(commands || []).forEach(k => {
mappedCommands[k] = makeCommand(commands[k]);
});
return mappedCommands;

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const Metro = require('metro');
@ -17,14 +20,16 @@ const {ASSET_REGISTRY_PATH} = require('../core/Constants');
function dependencies(argv, config, args, packagerInstance) {
const rootModuleAbsolutePath = args.entryFile;
if (!fs.existsSync(rootModuleAbsolutePath)) {
return Promise.reject(new Error(`File ${rootModuleAbsolutePath} does not exist`));
return Promise.reject(
new Error(`File ${rootModuleAbsolutePath} does not exist`),
);
}
const transformModulePath =
args.transformer ? path.resolve(args.transformer) :
typeof config.getTransformModulePath === 'function' ? config.getTransformModulePath() :
undefined;
const transformModulePath = args.transformer
? path.resolve(args.transformer)
: typeof config.getTransformModulePath === 'function'
? config.getTransformModulePath()
: undefined;
const packageOpts = {
assetRegistryPath: ASSET_REGISTRY_PATH,
@ -43,10 +48,7 @@ function dependencies(argv, config, args, packagerInstance) {
};
const relativePath = packageOpts.projectRoots.map(root =>
path.relative(
root,
rootModuleAbsolutePath
)
path.relative(root, rootModuleAbsolutePath),
)[0];
const options = {
@ -62,18 +64,19 @@ function dependencies(argv, config, args, packagerInstance) {
? fs.createWriteStream(args.output)
: process.stdout;
return Promise.resolve((packagerInstance ?
packagerInstance.getOrderedDependencyPaths(options) :
Metro.getOrderedDependencyPaths(packageOpts, options)).then(
deps => {
return Promise.resolve(
(packagerInstance
? packagerInstance.getOrderedDependencyPaths(options)
: Metro.getOrderedDependencyPaths(packageOpts, options)
).then(deps => {
deps.forEach(modulePath => {
// Temporary hack to disable listing dependencies not under this directory.
// Long term, we need either
// (a) JS code to not depend on anything outside this directory, or
// (b) Come up with a way to declare this dependency in Buck.
const isInsideProjectRoots = packageOpts.projectRoots.filter(
root => modulePath.startsWith(root)
).length > 0;
const isInsideProjectRoots =
packageOpts.projectRoots.filter(root => modulePath.startsWith(root))
.length > 0;
if (isInsideProjectRoots) {
outStream.write(modulePath + '\n');
@ -82,8 +85,8 @@ function dependencies(argv, config, args, packagerInstance) {
return writeToFile
? denodeify(outStream.end).bind(outStream)()
: Promise.resolve();
}
));
}),
);
}
module.exports = {
@ -94,27 +97,35 @@ module.exports = {
{
command: '--entry-file <path>',
description: 'Absolute path to the root JS file',
}, {
},
{
command: '--output [path]',
description: 'File name where to store the output, ex. /tmp/dependencies.txt',
}, {
description:
'File name where to store the output, ex. /tmp/dependencies.txt',
},
{
command: '--platform [extension]',
description: 'The platform extension used for selecting modules',
}, {
},
{
command: '--transformer [path]',
description: 'Specify a custom transformer to be used'
}, {
description: 'Specify a custom transformer to be used',
},
{
command: '--max-workers [number]',
description: 'Specifies the maximum number of workers the worker-pool ' +
description:
'Specifies the maximum number of workers the worker-pool ' +
'will spawn for transforming files. This defaults to the number of the ' +
'cores available on your machine.',
parse: (workers: string) => Number(workers),
}, {
},
{
command: '--dev [boolean]',
description: 'If false, skip all dev-only code path',
parse: (val) => val === 'false' ? false : true,
parse: val => (val === 'false' ? false : true),
default: true,
}, {
},
{
command: '--verbose',
description: 'Enables logging',
default: false,

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const copyProjectTemplateAndReplace = require('../generator/copyProjectTemplateAndReplace');
@ -22,13 +25,12 @@ const fs = require('fs');
*/
function eject() {
const doesIOSExist = fs.existsSync(path.resolve('ios'));
const doesAndroidExist = fs.existsSync(path.resolve('android'));
if (doesIOSExist && doesAndroidExist) {
console.error(
'Both the iOS and Android folders already exist! Please delete `ios` and/or `android` ' +
'before ejecting.'
'before ejecting.',
);
process.exit(1);
}
@ -39,8 +41,10 @@ function eject() {
} catch (e) {
console.error(
'Eject requires an `app.json` config file to be located at ' +
`${path.resolve('app.json')}, and it must at least specify a \`name\` for the project ` +
'name, and a `displayName` for the app\'s home screen label.'
`${path.resolve(
'app.json',
)}, and it must at least specify a \`name\` for the project ` +
"name, and a `displayName` for the app's home screen label.",
);
process.exit(1);
}
@ -49,7 +53,7 @@ function eject() {
if (!appName) {
console.error(
'App `name` must be defined in the `app.json` config file to define the project name. ' +
'It must not contain any spaces or dashes.'
'It must not contain any spaces or dashes.',
);
process.exit(1);
}
@ -57,33 +61,46 @@ function eject() {
if (!displayName) {
console.error(
'App `displayName` must be defined in the `app.json` config file, to define the label ' +
'of the app on the home screen.'
'of the app on the home screen.',
);
process.exit(1);
}
const templateOptions = { displayName };
const templateOptions = {displayName};
if (!doesIOSExist) {
console.log('Generating the iOS folder.');
copyProjectTemplateAndReplace(
path.resolve('node_modules', 'react-native', 'local-cli', 'templates', 'HelloWorld', 'ios'),
path.resolve(
'node_modules',
'react-native',
'local-cli',
'templates',
'HelloWorld',
'ios',
),
path.resolve('ios'),
appName,
templateOptions
templateOptions,
);
}
if (!doesAndroidExist) {
console.log('Generating the Android folder.');
copyProjectTemplateAndReplace(
path.resolve('node_modules', 'react-native', 'local-cli', 'templates', 'HelloWorld', 'android'),
path.resolve(
'node_modules',
'react-native',
'local-cli',
'templates',
'HelloWorld',
'android',
),
path.resolve('android'),
appName,
templateOptions
templateOptions,
);
}
}
module.exports = {

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const chalk = require('chalk');
@ -26,24 +29,42 @@ const walk = require('../util/walk');
* 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'); }
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');
}
options = options || {};
walk(srcPath).forEach(absoluteSrcFilePath => {
// 'react-native upgrade'
if (options.upgrade) {
// Don't upgrade these files
const fileName = path.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; }
if (fileName === 'index.ios.js') {
return;
}
if (fileName === 'index.android.js') {
return;
}
if (fileName === 'index.js') {
return;
}
if (fileName === 'App.js') {
return;
}
}
const relativeFilePath = path.relative(srcPath, absoluteSrcFilePath);
@ -59,14 +80,16 @@ function copyProjectTemplateAndReplace(srcPath, destPath, newProjectName, option
if (!Array.isArray(options.ignorePaths)) {
throw new Error('options.ignorePaths must be an array');
}
if (options.ignorePaths.some(ignorePath => ignorePath === relativeFilePath)) {
if (
options.ignorePaths.some(ignorePath => ignorePath === relativeFilePath)
) {
// Skip copying this file
return;
}
}
let contentChangedCallback = null;
if (options.upgrade && (!options.force)) {
if (options.upgrade && !options.force) {
contentChangedCallback = (_, contentChanged) => {
return upgradeFileContentChangedCallback(
absoluteSrcFilePath,
@ -80,8 +103,8 @@ function copyProjectTemplateAndReplace(srcPath, destPath, newProjectName, option
path.resolve(destPath, relativeRenamedPath),
{
'Hello App Display Name': options.displayName || newProjectName,
'HelloWorld': newProjectName,
'helloworld': newProjectName.toLowerCase(),
HelloWorld: newProjectName,
helloworld: newProjectName.toLowerCase(),
},
contentChangedCallback,
);
@ -97,7 +120,9 @@ function copyProjectTemplateAndReplace(srcPath, destPath, newProjectName, option
* behavior of automatically renaming .gitignore to .npmignore.
*/
function dotFilePath(path) {
if (!path) {return path;}
if (!path) {
return path;
}
return path
.replace('_gitignore', '.gitignore')
.replace('_gitattributes', '.gitattributes')
@ -110,20 +135,28 @@ function dotFilePath(path) {
function upgradeFileContentChangedCallback(
absoluteSrcFilePath,
relativeDestPath,
contentChanged
contentChanged,
) {
if (contentChanged === 'new') {
console.log(chalk.bold('new') + ' ' + relativeDestPath);
return 'overwrite';
} else if (contentChanged === 'changed') {
console.log(chalk.bold(relativeDestPath) + ' ' +
console.log(
chalk.bold(relativeDestPath) +
' ' +
'has changed in the new version.\nDo you want to keep your ' +
relativeDestPath + ' or replace it with the ' +
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: ');
"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') {
console.log('Replacing ' + relativeDestPath);
@ -135,7 +168,9 @@ function upgradeFileContentChangedCallback(
} else if (contentChanged === 'identical') {
return 'keep';
} else {
throw new Error(`Unknown file changed state: ${relativeDestPath}, ${contentChanged}`);
throw new Error(
`Unknown file changed state: ${relativeDestPath}, ${contentChanged}`,
);
}
}

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
var chalk = require('chalk');
@ -12,8 +15,12 @@ var path = require('path');
function printRunInstructions(projectDir, projectName) {
const absoluteProjectDir = path.resolve(projectDir);
// iOS
const xcodeProjectPath = path.resolve(projectDir, 'ios', projectName) + '.xcodeproj';
const relativeXcodeProjectPath = path.relative(process.cwd(), xcodeProjectPath);
const xcodeProjectPath =
path.resolve(projectDir, 'ios', projectName) + '.xcodeproj';
const relativeXcodeProjectPath = path.relative(
process.cwd(),
xcodeProjectPath,
);
console.log(chalk.white.bold('To run your app on iOS:'));
console.log(' cd ' + absoluteProjectDir);
console.log(' react-native run-ios');
@ -23,7 +30,9 @@ function printRunInstructions(projectDir, projectName) {
// Android
console.log(chalk.white.bold('To run your app on Android:'));
console.log(' cd ' + absoluteProjectDir);
console.log(' Have an Android emulator running (quickest way to get started), or a device connected');
console.log(
' Have an Android emulator running (quickest way to get started), or a device connected',
);
console.log(' react-native run-android');
}

View File

@ -1,3 +1,5 @@
/** @format */
// Simplified version of:
// https://github.com/0x00A/prompt-sync/blob/master/index.js
@ -7,11 +9,14 @@ var fs = require('fs');
var term = 13; // carriage return
function create() {
return prompt;
function prompt(ask, value, opts) {
var insert = 0, savedinsert = 0, res, i, savedstr;
var insert = 0,
savedinsert = 0,
res,
i,
savedstr;
opts = opts || {};
if (Object(ask) === ask) {
@ -25,15 +30,20 @@ function create() {
var echo = opts.echo;
var masked = 'echo' in opts;
var fd = (process.platform === 'win32') ?
process.stdin.fd :
fs.openSync('/dev/tty', 'rs');
var fd =
process.platform === 'win32'
? process.stdin.fd
: fs.openSync('/dev/tty', 'rs');
var wasRaw = process.stdin.isRaw;
if (!wasRaw) { process.stdin.setRawMode(true); }
if (!wasRaw) {
process.stdin.setRawMode(true);
}
var buf = new Buffer(3);
var str = '', character, read;
var str = '',
character,
read;
savedstr = '';
@ -46,7 +56,8 @@ function create() {
while (true) {
read = fs.readSync(fd, buf, 0, 3);
if (read > 1) { // received a control sequence
if (read > 1) {
// received a control sequence
if (buf.toString()) {
str = str + buf.toString();
str = str.replace(/\0/g, '');
@ -62,7 +73,7 @@ function create() {
character = buf[read - 1];
// catch a ^C and return null
if (character == 3){
if (character == 3) {
process.stdout.write('^C\n');
fs.closeSync(fd);
process.exit(130);
@ -76,20 +87,29 @@ function create() {
break;
}
if (character == 127 || (process.platform == 'win32' && character == 8)) { //backspace
if (!insert) {continue;}
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);
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));
process.stdout.write(
'\u001b[2K\u001b[0G' + ask + Array(str.length + 1).join(echo),
);
} else {
process.stdout.write('\u001b[s');
if (insert == str.length) {
@ -98,13 +118,18 @@ function create() {
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[2K\u001b[0G' +
str +
'\u001b[' +
(str.length - insert) +
'D',
);
}
}
process.stdout.write('\u001b[u');
process.stdout.write('\u001b[1C');
}
}
process.stdout.write('\n');

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const copyProjectTemplateAndReplace = require('./copyProjectTemplateAndReplace');
@ -29,7 +32,7 @@ function listTemplatesAndExit(newProjectName, options) {
// above is defined correctly :)
console.log(
'There are no templates available besides ' +
'the default "Hello World" one.'
'the default "Hello World" one.',
);
} else {
console.log(
@ -37,7 +40,10 @@ function listTemplatesAndExit(newProjectName, options) {
templateKeys.join('\n') +
'\nYou can use these to create an app based on a template, for example: ' +
'you could run: ' +
'react-native init ' + newProjectName + ' --template ' + templateKeys[0]
'react-native init ' +
newProjectName +
' --template ' +
templateKeys[0],
);
}
// Exit 'react-native init'
@ -54,12 +60,23 @@ function listTemplatesAndExit(newProjectName, options) {
* @param yarnVersion Version of yarn available on the system, or null if
* yarn is not available. For example '0.18.1'.
*/
function createProjectFromTemplate(destPath, newProjectName, template, yarnVersion) {
function createProjectFromTemplate(
destPath,
newProjectName,
template,
yarnVersion,
) {
// Expand the basic 'HelloWorld' template
copyProjectTemplateAndReplace(
path.resolve('node_modules', 'react-native', 'local-cli', 'templates', 'HelloWorld'),
path.resolve(
'node_modules',
'react-native',
'local-cli',
'templates',
'HelloWorld',
),
destPath,
newProjectName
newProjectName,
);
if (template === undefined) {
@ -79,7 +96,12 @@ function createProjectFromTemplate(destPath, newProjectName, template, yarnVersi
if (builtInTemplateName) {
// template is e.g. 'navigation',
// use the built-in local-cli/templates/HelloNavigation folder
createFromBuiltInTemplate(builtInTemplateName, destPath, newProjectName, yarnVersion);
createFromBuiltInTemplate(
builtInTemplateName,
destPath,
newProjectName,
yarnVersion,
);
} else {
// template is e.g. 'ignite',
// use the template react-native-template-ignite from npm
@ -89,15 +111,20 @@ function createProjectFromTemplate(destPath, newProjectName, template, yarnVersi
// (We might want to get rid of built-in templates in the future -
// publish them to npm and install from there.)
function createFromBuiltInTemplate(templateName, destPath, newProjectName, yarnVersion) {
const templatePath = path.resolve(
'node_modules', 'react-native', 'local-cli', 'templates', templateName
);
copyProjectTemplateAndReplace(
templatePath,
function createFromBuiltInTemplate(
templateName,
destPath,
newProjectName,
yarnVersion,
) {
const templatePath = path.resolve(
'node_modules',
'react-native',
'local-cli',
'templates',
templateName,
);
copyProjectTemplateAndReplace(templatePath, destPath, newProjectName);
installTemplateDependencies(templatePath, yarnVersion);
installTemplateDevDependencies(templatePath, yarnVersion);
}
@ -107,7 +134,12 @@ function createFromBuiltInTemplate(templateName, destPath, newProjectName, yarnV
* - 'demo' -> Fetch the package react-native-template-demo from npm
* - git://..., http://..., file://... or any other URL supported by npm
*/
function createFromRemoteTemplate(template, destPath, newProjectName, yarnVersion) {
function createFromRemoteTemplate(
template,
destPath,
newProjectName,
yarnVersion,
) {
let installPackage;
let templateName;
if (template.includes('://')) {
@ -124,25 +156,23 @@ function createFromRemoteTemplate(template, destPath, newProjectName, yarnVersio
console.log(`Fetching template ${installPackage}...`);
try {
if (yarnVersion) {
execSync(`yarn add ${installPackage} --ignore-scripts`, {stdio: 'inherit'});
execSync(`yarn add ${installPackage} --ignore-scripts`, {
stdio: 'inherit',
});
} else {
execSync(`npm install ${installPackage} --save --save-exact --ignore-scripts`, {stdio: 'inherit'});
}
const templatePath = path.resolve(
'node_modules', templateName
execSync(
`npm install ${installPackage} --save --save-exact --ignore-scripts`,
{stdio: 'inherit'},
);
copyProjectTemplateAndReplace(
templatePath,
destPath,
newProjectName,
{
}
const templatePath = path.resolve('node_modules', templateName);
copyProjectTemplateAndReplace(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'],
}
);
});
installTemplateDependencies(templatePath, yarnVersion);
installTemplateDevDependencies(templatePath, yarnVersion);
} finally {
@ -158,7 +188,7 @@ function createFromRemoteTemplate(template, destPath, newProjectName, yarnVersio
// if this the clean up fails.
console.warn(
`Failed to clean up template temp files in node_modules/${templateName}. ` +
'This is not a critical error, you can work on your app.'
'This is not a critical error, you can work on your app.',
);
}
}
@ -167,9 +197,7 @@ function createFromRemoteTemplate(template, destPath, newProjectName, yarnVersio
function installTemplateDependencies(templatePath, yarnVersion) {
// dependencies.json is a special file that lists additional dependencies
// that are required by this template
const dependenciesJsonPath = path.resolve(
templatePath, 'dependencies.json'
);
const dependenciesJsonPath = path.resolve(templatePath, 'dependencies.json');
console.log('Adding dependencies for the project...');
if (!fs.existsSync(dependenciesJsonPath)) {
console.log('No additional dependencies.');
@ -181,7 +209,7 @@ function installTemplateDependencies(templatePath, yarnVersion) {
dependencies = JSON.parse(fs.readFileSync(dependenciesJsonPath));
} catch (err) {
throw new Error(
'Could not parse the template\'s dependencies.json: ' + err.message
"Could not parse the template's dependencies.json: " + err.message,
);
}
for (let depName in dependencies) {
@ -191,10 +219,12 @@ function installTemplateDependencies(templatePath, yarnVersion) {
if (yarnVersion) {
execSync(`yarn add ${depToInstall}`, {stdio: 'inherit'});
} else {
execSync(`npm install ${depToInstall} --save --save-exact`, {stdio: 'inherit'});
execSync(`npm install ${depToInstall} --save --save-exact`, {
stdio: 'inherit',
});
}
}
console.log('Linking native dependencies into the project\'s build files...');
console.log("Linking native dependencies into the project's build files...");
execSync('react-native link', {stdio: 'inherit'});
}
@ -202,7 +232,8 @@ function installTemplateDevDependencies(templatePath, yarnVersion) {
// devDependencies.json is a special file that lists additional develop dependencies
// that are required by this template
const devDependenciesJsonPath = path.resolve(
templatePath, 'devDependencies.json'
templatePath,
'devDependencies.json',
);
console.log('Adding develop dependencies for the project...');
if (!fs.existsSync(devDependenciesJsonPath)) {
@ -215,7 +246,7 @@ function installTemplateDevDependencies(templatePath, yarnVersion) {
dependencies = JSON.parse(fs.readFileSync(devDependenciesJsonPath));
} catch (err) {
throw new Error(
'Could not parse the template\'s devDependencies.json: ' + err.message
"Could not parse the template's devDependencies.json: " + err.message,
);
}
for (let depName in dependencies) {
@ -225,7 +256,9 @@ function installTemplateDevDependencies(templatePath, yarnVersion) {
if (yarnVersion) {
execSync(`yarn add ${depToInstall} -D`, {stdio: 'inherit'});
} else {
execSync(`npm install ${depToInstall} --save-dev --save-exact`, {stdio: 'inherit'});
execSync(`npm install ${depToInstall} --save-dev --save-exact`, {
stdio: 'inherit',
});
}
}
}

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const envinfo = require('envinfo');
@ -13,7 +16,10 @@ const info = function() {
try {
envinfo.print({
packages: typeof args.packages === 'string' ? ['react', 'react-native'].concat(args.packages.split(',')) : args.packages
packages:
typeof args.packages === 'string'
? ['react', 'react-native'].concat(args.packages.split(','))
: args.packages,
});
} catch (error) {
console.log('Error: unable to print environment info');
@ -27,8 +33,9 @@ module.exports = {
options: [
{
command: '--packages [string]',
description: 'Which packages from your package.json to include, in addition to the default React Native and React versions.',
default: ['react', 'react-native']
description:
'Which packages from your package.json to include, in addition to the default React Native and React versions.',
default: ['react', 'react-native'],
},
],
examples: [
@ -39,7 +46,7 @@ module.exports = {
{
desc: 'Get standard version info & specified package versions',
cmd: 'react-native info --packages jest,eslint,babel-polyfill',
}
},
],
func: info,
};

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const {
@ -58,42 +61,53 @@ function init(projectDir, argsOrName) {
*/
function generateProject(destinationRoot, newProjectName, options) {
var reactNativePackageJson = require('../../package.json');
var { peerDependencies } = reactNativePackageJson;
var {peerDependencies} = reactNativePackageJson;
if (!peerDependencies) {
console.error('Missing React peer dependency in React Native\'s package.json. Aborting.');
console.error(
"Missing React peer dependency in React Native's package.json. Aborting.",
);
return;
}
var reactVersion = peerDependencies.react;
if (!reactVersion) {
console.error('Missing React peer dependency in React Native\'s package.json. Aborting.');
console.error(
"Missing React peer dependency in React Native's package.json. Aborting.",
);
return;
}
const yarnVersion =
(!options.npm) &&
!options.npm &&
yarn.getYarnVersionIfAvailable() &&
yarn.isGlobalCliUsingYarn(destinationRoot);
createProjectFromTemplate(destinationRoot, newProjectName, options.template, yarnVersion);
createProjectFromTemplate(
destinationRoot,
newProjectName,
options.template,
yarnVersion,
);
if (yarnVersion) {
console.log('Adding React...');
execSync(`yarn add react@${reactVersion}`, {stdio: 'inherit'});
} else {
console.log('Installing React...');
execSync(`npm install react@${reactVersion} --save --save-exact`, {stdio: 'inherit'});
execSync(`npm install react@${reactVersion} --save --save-exact`, {
stdio: 'inherit',
});
}
if (!options['skip-jest']) {
const jestDeps = (
`jest babel-jest babel-preset-react-native react-test-renderer@${reactVersion}`
);
const jestDeps = `jest babel-jest babel-preset-react-native react-test-renderer@${reactVersion}`;
if (yarnVersion) {
console.log('Adding Jest...');
execSync(`yarn add ${jestDeps} --dev --exact`, {stdio: 'inherit'});
} else {
console.log('Installing Jest...');
execSync(`npm install ${jestDeps} --save-dev --save-exact`, {stdio: 'inherit'});
execSync(`npm install ${jestDeps} --save-dev --save-exact`, {
stdio: 'inherit',
});
}
addJestToPackageJson(destinationRoot);
}
@ -109,7 +123,7 @@ function addJestToPackageJson(destinationRoot) {
packageJSON.scripts.test = 'jest';
packageJSON.jest = {
preset: 'react-native'
preset: 'react-native',
};
fs.writeFileSync(packageJSONPath, JSON.stringify(packageJSON, null, 2));
}

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const spawnSync = require('child_process').spawnSync;

View File

@ -3,7 +3,10 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const spawnSync = require('child_process').spawnSync;

View File

@ -1,9 +1,12 @@
/**
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const copyAndReplace = require('../util/copyAndReplace');
@ -18,36 +21,47 @@ const walk = require('../util/walk');
function library(argv, config, args) {
if (!isValidPackageName(args.name)) {
return Promise.reject(
args.name + ' is not a valid name for a project. Please use a valid ' +
'identifier name (alphanumeric).'
args.name +
' is not a valid name for a project. Please use a valid ' +
'identifier name (alphanumeric).',
);
}
const root = process.cwd();
const libraries = path.resolve(root, 'Libraries');
const libraryDest = path.resolve(libraries, args.name);
const source = path.resolve('node_modules', 'react-native', 'Libraries', 'Sample');
const source = path.resolve(
'node_modules',
'react-native',
'Libraries',
'Sample',
);
if (!fs.existsSync(libraries)) {
fs.mkdirSync(libraries);
}
if (fs.existsSync(libraryDest)) {
return Promise.reject(new Error(`Library already exists in ${libraryDest}`));
return Promise.reject(
new Error(`Library already exists in ${libraryDest}`),
);
}
walk(source).forEach(f => {
if (f.indexOf('project.xcworkspace') !== -1 ||
f.indexOf('.xcodeproj/xcuserdata') !== -1) {
if (
f.indexOf('project.xcworkspace') !== -1 ||
f.indexOf('.xcodeproj/xcuserdata') !== -1
) {
return;
}
const dest = path.relative(source, f.replace(/Sample/g, args.name).replace(/^_/, '.'));
copyAndReplace(
path.resolve(source, f),
path.resolve(libraryDest, dest),
{'Sample': args.name}
const dest = path.relative(
source,
f.replace(/Sample/g, args.name).replace(/^_/, '.'),
);
copyAndReplace(path.resolve(source, f), path.resolve(libraryDest, dest), {
Sample: args.name,
});
});
console.log('Created library in', libraryDest);
@ -55,7 +69,7 @@ function library(argv, config, args) {
console.log(' Link your library in Xcode:');
console.log(
' https://facebook.github.io/react-native/docs/' +
'linking-libraries-ios.html#content\n'
'linking-libraries-ios.html#content\n',
);
}
@ -63,9 +77,11 @@ module.exports = {
name: 'new-library',
func: library,
description: 'generates a native library bridge',
options: [{
options: [
{
command: '--name <string>',
description: 'name of the library to generate',
default: null,
}],
},
],
};

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -13,14 +14,12 @@ const applyParams = require('../../android/patches/applyParams');
describe('applyParams', () => {
it('apply params to the string', () => {
expect(
applyParams('${foo}', {foo: 'foo'}, 'react-native')
).toEqual('getResources().getString(R.string.reactNative_foo)');
expect(applyParams('${foo}', {foo: 'foo'}, 'react-native')).toEqual(
'getResources().getString(R.string.reactNative_foo)',
);
});
it('use null if no params provided', () => {
expect(
applyParams('${foo}', {}, 'react-native')
).toEqual('null');
expect(applyParams('${foo}', {}, 'react-native')).toEqual('null');
});
});

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -13,7 +14,10 @@ const path = require('path');
const isInstalled = require('../../android/isInstalled');
const projectConfig = {
buildGradlePath: path.join(__dirname, '../../__fixtures__/android/patchedBuild.gradle'),
buildGradlePath: path.join(
__dirname,
'../../__fixtures__/android/patchedBuild.gradle',
),
};
describe('android::isInstalled', () => {
@ -23,6 +27,5 @@ describe('android::isInstalled', () => {
});
it('should return false when project is not in build.gradle', () =>
expect(isInstalled(projectConfig, 'test3')).toBeFalsy()
);
expect(isInstalled(projectConfig, 'test3')).toBeFalsy());
});

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -18,8 +19,9 @@ const normalizedScopedName = normalizeProjectName('@scoped/test');
describe('makeBuildPatch', () => {
it('should build a patch function', () => {
expect(Object.prototype.toString(makeBuildPatch(name)))
.toBe('[object Object]');
expect(Object.prototype.toString(makeBuildPatch(name))).toBe(
'[object Object]',
);
});
it('should make a correct patch', () => {
@ -34,7 +36,6 @@ describe('makeBuildPatch', () => {
});
});
describe('makeBuildPatchWithScopedPackage', () => {
it('should make a correct patch', () => {
const {patch} = makeBuildPatch(scopedName);

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -15,8 +16,9 @@ const packageImportPath = 'import some.example.project';
describe('makeImportPatch', () => {
it('should build a patch', () => {
expect(Object.prototype.toString(makeImportPatch(packageImportPath)))
.toBe('[object Object]');
expect(Object.prototype.toString(makeImportPatch(packageImportPath))).toBe(
'[object Object]',
);
});
it('MainActivity contains a correct import patch', () => {

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -12,7 +13,7 @@
const makePackagePatch = require('../../android/patches/makePackagePatch');
const applyParams = require('../../android/patches/applyParams');
const packageInstance = 'new SomeLibrary(${foo}, ${bar}, \'something\')';
const packageInstance = "new SomeLibrary(${foo}, ${bar}, 'something')";
const name = 'some-library';
const params = {
foo: 'foo',
@ -22,8 +23,7 @@ const params = {
describe('makePackagePatch@0.20', () => {
it('should build a patch', () => {
const packagePatch = makePackagePatch(packageInstance, params, name);
expect(Object.prototype.toString(packagePatch))
.toBe('[object Object]');
expect(Object.prototype.toString(packagePatch)).toBe('[object Object]');
});
it('MainActivity contains a correct 0.20 import patch', () => {

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -29,48 +30,54 @@ const scopedDependencyConfig = {
describe('makeSettingsPatch', () => {
it('should build a patch function', () => {
expect(Object.prototype.toString(
makeSettingsPatch(name, dependencyConfig, projectConfig)
)).toBe('[object Object]');
expect(
Object.prototype.toString(
makeSettingsPatch(name, dependencyConfig, projectConfig),
),
).toBe('[object Object]');
});
it('should make a correct patch', () => {
const projectDir = path.relative(
path.dirname(projectConfig.settingsGradlePath),
dependencyConfig.sourceDir
dependencyConfig.sourceDir,
);
const {patch} = makeSettingsPatch(name, dependencyConfig, projectConfig);
expect(patch)
.toBe(
expect(patch).toBe(
`include ':${name}'\n` +
`project(':${name}').projectDir = ` +
`new File(rootProject.projectDir, '${projectDir}')\n`
`new File(rootProject.projectDir, '${projectDir}')\n`,
);
});
});
describe('makeSettingsPatchWithScopedPackage', () => {
it('should build a patch function', () => {
expect(Object.prototype.toString(
makeSettingsPatch(scopedName, scopedDependencyConfig, projectConfig)
)).toBe('[object Object]');
expect(
Object.prototype.toString(
makeSettingsPatch(scopedName, scopedDependencyConfig, projectConfig),
),
).toBe('[object Object]');
});
it('should make a correct patch', () => {
const projectDir = path.relative(
path.dirname(projectConfig.settingsGradlePath),
scopedDependencyConfig.sourceDir
scopedDependencyConfig.sourceDir,
);
const {patch} = makeSettingsPatch(scopedName, scopedDependencyConfig, projectConfig);
const {patch} = makeSettingsPatch(
scopedName,
scopedDependencyConfig,
projectConfig,
);
expect(patch)
.toBe(
expect(patch).toBe(
`include ':${normalizedScopedName}'\n` +
`project(':${normalizedScopedName}').projectDir = ` +
`new File(rootProject.projectDir, '${projectDir}')\n`
`new File(rootProject.projectDir, '${projectDir}')\n`,
);
});
});

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -17,8 +18,9 @@ describe('makeStringsPatch', () => {
keyA: 'valueA',
};
expect(makeStringsPatch(params, 'module').patch)
.toContain('<string moduleConfig="true" name="module_keyA">valueA</string>');
expect(makeStringsPatch(params, 'module').patch).toContain(
'<string moduleConfig="true" name="module_keyA">valueA</string>',
);
});
it('should export an empty patch if no params given', () => {

View File

@ -6,21 +6,20 @@
*
* All rights reserved.
*
* @format
* @emails oncall+javascript_foundation
*/
'use strict';
'use strict';
const normalizeProjectName = require('../../android/patches/normalizeProjectName');
const name = 'test';
const scopedName = '@scoped/test';
describe('normalizeProjectName', () => {
describe('normalizeProjectName', () => {
it('should replace slashes with underscores', () => {
expect(normalizeProjectName(name))
.toBe('test');
expect(normalizeProjectName(scopedName))
.toBe('@scoped_test');
expect(normalizeProjectName(name)).toBe('test');
expect(normalizeProjectName(scopedName)).toBe('@scoped_test');
});
});

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -13,7 +14,7 @@ const getDependencyConfig = require('../getDependencyConfig');
const sinon = require('sinon');
describe('getDependencyConfig', () => {
it('should return an array of dependencies\' rnpm config', () => {
it("should return an array of dependencies' rnpm config", () => {
const config = {
getDependencyConfig: sinon.stub(),
};

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -17,10 +18,9 @@ describe('getProjectDependencies', () => {
jest.resetModules();
});
it('should return an array of project dependencies', () => {
jest.setMock(
path.join(process.cwd(), './package.json'),
{ dependencies: { lodash: '^6.0.0', 'react-native': '^16.0.0' }}
);
jest.setMock(path.join(process.cwd(), './package.json'), {
dependencies: {lodash: '^6.0.0', 'react-native': '^16.0.0'},
});
expect(getProjectDependencies()).toEqual(['lodash']);
});

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -12,21 +13,13 @@
const groupFilesByType = require('../groupFilesByType');
describe('groupFilesByType', () => {
it('should group files by its type', () => {
const fonts = [
'fonts/a.ttf',
'fonts/b.ttf',
];
const images = [
'images/a.jpg',
'images/c.jpeg',
];
const fonts = ['fonts/a.ttf', 'fonts/b.ttf'];
const images = ['images/a.jpg', 'images/c.jpeg'];
const groupedFiles = groupFilesByType(fonts.concat(images));
expect(groupedFiles.font).toEqual(fonts);
expect(groupedFiles.image).toEqual(images);
});
});

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -15,7 +16,7 @@ const addFileToProject = require('../../ios/addFileToProject');
const _ = require('lodash');
const project = xcode.project(
path.join(__dirname, '../../__fixtures__/project.pbxproj')
path.join(__dirname, '../../__fixtures__/project.pbxproj'),
);
describe('ios::addFileToProject', () => {
@ -27,8 +28,9 @@ describe('ios::addFileToProject', () => {
expect(
_.includes(
Object.keys(project.pbxFileReferenceSection()),
addFileToProject(project, '../../__fixtures__/linearGradient.pbxproj').fileRef
)
addFileToProject(project, '../../__fixtures__/linearGradient.pbxproj')
.fileRef,
),
).toBeTruthy();
});
});

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -16,7 +17,7 @@ const addProjectToLibraries = require('../../ios/addProjectToLibraries');
const last = require('lodash').last;
const project = xcode.project(
path.join(__dirname, '../../__fixtures__/project.pbxproj')
path.join(__dirname, '../../__fixtures__/project.pbxproj'),
);
describe('ios::addProjectToLibraries', () => {

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -15,11 +16,10 @@ const addSharedLibraries = require('../../ios/addSharedLibraries');
const getGroup = require('../../ios/getGroup');
const project = xcode.project(
path.join(__dirname, '../../__fixtures__/project.pbxproj')
path.join(__dirname, '../../__fixtures__/project.pbxproj'),
);
describe('ios::addSharedLibraries', () => {
beforeEach(() => {
project.parseSync();
});
@ -48,5 +48,4 @@ describe('ios::addSharedLibraries', () => {
const frameworksGroup = getGroup(project, 'Frameworks');
expect(frameworksGroup.children.length).toEqual(1);
});
});

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -16,7 +17,7 @@ const getGroup = require('../../ios/getGroup');
const last = require('lodash').last;
const project = xcode.project(
path.join(__dirname, '../../__fixtures__/project.pbxproj')
path.join(__dirname, '../../__fixtures__/project.pbxproj'),
);
describe('ios::createGroup', () => {
@ -33,18 +34,14 @@ describe('ios::createGroup', () => {
const createdGroup = createGroup(project, 'Resources');
const mainGroup = getGroup(project);
expect(
last(mainGroup.children).comment
).toBe(createdGroup.name);
expect(last(mainGroup.children).comment).toBe(createdGroup.name);
});
it('should create a nested group with given path', () => {
const createdGroup = createGroup(project, 'NewGroup/NewNestedGroup');
const outerGroup = getGroup(project, 'NewGroup');
expect(
last(outerGroup.children).comment
).toBe(createdGroup.name);
expect(last(outerGroup.children).comment).toBe(createdGroup.name);
});
it('should-not create already created groups', () => {
@ -53,10 +50,7 @@ describe('ios::createGroup', () => {
const mainGroup = getGroup(project);
expect(
mainGroup
.children
.filter(group => group.comment === 'Libraries')
.length
mainGroup.children.filter(group => group.comment === 'Libraries').length,
).toBe(1);
expect(last(outerGroup.children).comment).toBe(createdGroup.name);
});

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -14,7 +15,7 @@ const path = require('path');
const getBuildProperty = require('../../ios/getBuildProperty');
const project = xcode.project(
path.join(__dirname, '../../__fixtures__/project.pbxproj')
path.join(__dirname, '../../__fixtures__/project.pbxproj'),
);
describe('ios::getBuildProperty', () => {

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -14,7 +15,7 @@ const getGroup = require('../../ios/getGroup');
const path = require('path');
const project = xcode.project(
path.join(__dirname, '../../__fixtures__/project.pbxproj')
path.join(__dirname, '../../__fixtures__/project.pbxproj'),
);
describe('ios::getGroup', () => {

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -20,14 +21,19 @@ describe('ios::getHeaderSearchPath', () => {
*/
it('should return correct path when all headers are in root folder', () => {
const files = [
path.join('react-native-project', 'node_modules', 'package', 'Gradient.h'),
path.join(
'react-native-project',
'node_modules',
'package',
'Gradient.h',
),
path.join('react-native-project', 'node_modules', 'package', 'Manager.h'),
];
const searchPath = getHeaderSearchPath(SRC_DIR, files);
expect(searchPath).toBe(
`"${['$(SRCROOT)', '..', 'node_modules', 'package'].join(path.sep)}"`
`"${['$(SRCROOT)', '..', 'node_modules', 'package'].join(path.sep)}"`,
);
});
@ -36,14 +42,30 @@ describe('ios::getHeaderSearchPath', () => {
*/
it('should return correct path when headers are in multiple folders', () => {
const files = [
path.join('react-native-project', 'node_modules', 'package', 'src', 'folderA', 'Gradient.h'),
path.join('react-native-project', 'node_modules', 'package', 'src', 'folderB', 'Manager.h'),
path.join(
'react-native-project',
'node_modules',
'package',
'src',
'folderA',
'Gradient.h',
),
path.join(
'react-native-project',
'node_modules',
'package',
'src',
'folderB',
'Manager.h',
),
];
const searchPath = getHeaderSearchPath(SRC_DIR, files);
expect(searchPath).toBe(
`"${['$(SRCROOT)', '..', 'node_modules', 'package', 'src'].join(path.sep)}/**"`
`"${['$(SRCROOT)', '..', 'node_modules', 'package', 'src'].join(
path.sep,
)}/**"`,
);
});
@ -52,15 +74,37 @@ describe('ios::getHeaderSearchPath', () => {
*/
it('should return correct path when headers are in root and nested folders', () => {
const files = [
path.join('react-native-project', 'node_modules', 'package', 'src', 'folderA', 'Gradient.h'),
path.join('react-native-project', 'node_modules', 'package', 'src', 'folderB', 'Manager.h'),
path.join('react-native-project', 'node_modules', 'package', 'src', 'Manager.h'),
path.join(
'react-native-project',
'node_modules',
'package',
'src',
'folderA',
'Gradient.h',
),
path.join(
'react-native-project',
'node_modules',
'package',
'src',
'folderB',
'Manager.h',
),
path.join(
'react-native-project',
'node_modules',
'package',
'src',
'Manager.h',
),
];
const searchPath = getHeaderSearchPath(SRC_DIR, files);
expect(searchPath).toBe(
`"${['$(SRCROOT)', '..', 'node_modules', 'package', 'src'].join(path.sep)}/**"`
`"${['$(SRCROOT)', '..', 'node_modules', 'package', 'src'].join(
path.sep,
)}/**"`,
);
});
});

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -14,7 +15,7 @@ const getPlist = require('../../ios/getPlist');
const path = require('path');
const project = xcode.project(
path.join(__dirname, '../../__fixtures__/project.pbxproj')
path.join(__dirname, '../../__fixtures__/project.pbxproj'),
);
describe('ios::getPlist', () => {

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -14,7 +15,7 @@ const getPlistPath = require('../../ios/getPlistPath');
const path = require('path');
const project = xcode.project(
path.join(__dirname, '../../__fixtures__/project.pbxproj')
path.join(__dirname, '../../__fixtures__/project.pbxproj'),
);
describe('ios::getPlistPath', () => {

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -14,7 +15,7 @@ const getProducts = require('../../ios/getProducts');
const path = require('path');
const project = xcode.project(
path.join(__dirname, '../../__fixtures__/project.pbxproj')
path.join(__dirname, '../../__fixtures__/project.pbxproj'),
);
describe('ios::getProducts', () => {

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -14,7 +15,7 @@ const getTargets = require('../../ios/getTargets');
const path = require('path');
const project = xcode.project(
path.join(__dirname, '../../__fixtures__/project.pbxproj')
path.join(__dirname, '../../__fixtures__/project.pbxproj'),
);
describe('ios::getTargets', () => {

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -14,7 +15,7 @@ const hasLibraryImported = require('../../ios/hasLibraryImported');
const path = require('path');
const project = xcode.project(
path.join(__dirname, '../../__fixtures__/project.pbxproj')
path.join(__dirname, '../../__fixtures__/project.pbxproj'),
);
describe('ios::hasLibraryImported', () => {

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -19,18 +20,20 @@ const baseProjectConfig = {
describe('ios::isInstalled', () => {
it('should return true when .xcodeproj in Libraries', () => {
const dependencyConfig = { projectName: 'React.xcodeproj' };
const dependencyConfig = {projectName: 'React.xcodeproj'};
expect(isInstalled(baseProjectConfig, dependencyConfig)).toBeTruthy();
});
it('should return false when .xcodeproj not in Libraries', () => {
const dependencyConfig = { projectName: 'Missing.xcodeproj' };
const dependencyConfig = {projectName: 'Missing.xcodeproj'};
expect(isInstalled(baseProjectConfig, dependencyConfig)).toBeFalsy();
});
it('should return false when `LibraryFolder` is missing', () => {
const dependencyConfig = { projectName: 'React.xcodeproj' };
const projectConfig = Object.assign({}, baseProjectConfig, { libraryFolder: 'Missing' });
const dependencyConfig = {projectName: 'React.xcodeproj'};
const projectConfig = Object.assign({}, baseProjectConfig, {
libraryFolder: 'Missing',
});
expect(isInstalled(projectConfig, dependencyConfig)).toBeFalsy();
});
});

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -14,7 +15,7 @@ const mapHeaderSearchPaths = require('../../ios/mapHeaderSearchPaths');
const path = require('path');
const project = xcode.project(
path.join(__dirname, '../../__fixtures__/project.pbxproj')
path.join(__dirname, '../../__fixtures__/project.pbxproj'),
);
describe('ios::mapHeaderSearchPaths', () => {

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -17,7 +18,7 @@ const last = require('lodash').last;
const path = require('path');
const project = xcode.project(
path.join(__dirname, '../../__fixtures__/project.pbxproj')
path.join(__dirname, '../../__fixtures__/project.pbxproj'),
);
describe('ios::removeProjectFromLibraries', () => {
@ -26,7 +27,7 @@ describe('ios::removeProjectFromLibraries', () => {
addProjectToLibraries(
project.pbxGroupByName('Libraries'),
new PbxFile('fakePath')
new PbxFile('fakePath'),
);
});

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -16,7 +17,7 @@ const removeProjectFromProject = require('../../ios/removeProjectFromProject');
const path = require('path');
const project = xcode.project(
path.join(__dirname, '../../__fixtures__/project.pbxproj')
path.join(__dirname, '../../__fixtures__/project.pbxproj'),
);
const filePath = '../../__fixtures__/linearGradient.pbxproj';
@ -27,8 +28,9 @@ describe('ios::addFileToProject', () => {
});
it('should return removed file', () => {
expect(removeProjectFromProject(project, filePath) instanceof pbxFile)
.toBeTruthy();
expect(
removeProjectFromProject(project, filePath) instanceof pbxFile,
).toBeTruthy();
});
it('should remove file from a project', () => {

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -16,11 +17,10 @@ const removeSharedLibraries = require('../../ios/removeSharedLibraries');
const getGroup = require('../../ios/getGroup');
const project = xcode.project(
path.join(__dirname, '../../__fixtures__/project.pbxproj')
path.join(__dirname, '../../__fixtures__/project.pbxproj'),
);
describe('ios::removeSharedLibraries', () => {
beforeEach(() => {
project.parseSync();
addSharedLibraries(project, ['libc++.tbd', 'libz.tbd']);
@ -40,5 +40,4 @@ describe('ios::removeSharedLibraries', () => {
const frameworksGroup = getGroup(project, 'Frameworks');
expect(frameworksGroup.children.length).toEqual(2);
});
});

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -14,7 +15,7 @@ jest.mock('fs');
let plistPath = null;
jest.mock('../../ios/getPlistPath', () => () => plistPath);
const { readFileSync } = require.requireActual('fs');
const {readFileSync} = require.requireActual('fs');
const fs = require('fs');
const xcode = require('xcode');
@ -33,9 +34,7 @@ const project = xcode.project('/Basic/project.pbxproj');
const plist = {
CFBundleDevelopmentRegion: 'en',
UISupportedInterfaceOrientations: [
'UIInterfaceOrientationPortrait'
]
UISupportedInterfaceOrientations: ['UIInterfaceOrientationPortrait'],
};
describe('ios::writePlist', () => {

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -12,10 +13,7 @@
const sinon = require('sinon');
const log = require('npmlog');
const path = require('path');
jest.setMock(
'chalk',
{ grey: (str) => str, }
);
jest.setMock('chalk', {grey: str => str});
describe('link', () => {
beforeEach(() => {
@ -24,7 +22,7 @@ describe('link', () => {
log.level = 'silent';
});
it('should reject when run in a folder without package.json', (done) => {
it('should reject when run in a folder without package.json', done => {
const config = {
getProjectConfig: () => {
throw new Error('No package.json found');
@ -35,77 +33,65 @@ describe('link', () => {
link([], config).catch(() => done());
});
it('should accept a name of a dependency to link', (done) => {
it('should accept a name of a dependency to link', done => {
const config = {
getPlatformConfig: () => ({ios: {}, android: {}}),
getProjectConfig: () => ({ assets: [] }),
getDependencyConfig: sinon.stub().returns({ assets: [], commands: {} }),
getProjectConfig: () => ({assets: []}),
getDependencyConfig: sinon.stub().returns({assets: [], commands: {}}),
};
const link = require('../link').func;
link(['react-native-gradient'], config).then(() => {
expect(
config.getDependencyConfig.calledWith('react-native-gradient')
config.getDependencyConfig.calledWith('react-native-gradient'),
).toBeTruthy();
done();
});
});
it('should read dependencies from package.json when name not provided', (done) => {
it('should read dependencies from package.json when name not provided', done => {
const config = {
getPlatformConfig: () => ({ios: {}, android: {}}),
getProjectConfig: () => ({ assets: [] }),
getDependencyConfig: sinon.stub().returns({ assets: [], commands: {} }),
getProjectConfig: () => ({assets: []}),
getDependencyConfig: sinon.stub().returns({assets: [], commands: {}}),
};
jest.setMock(
path.join(process.cwd(), 'package.json'),
{
jest.setMock(path.join(process.cwd(), 'package.json'), {
dependencies: {
'react-native-test': '*',
},
}
);
});
const link = require('../link').func;
link([], config).then(() => {
expect(
config.getDependencyConfig.calledWith('react-native-test')
config.getDependencyConfig.calledWith('react-native-test'),
).toBeTruthy();
done();
});
});
it('should register native module when android/ios projects are present', (done) => {
it('should register native module when android/ios projects are present', done => {
const registerNativeModule = sinon.stub();
const dependencyConfig = {android: {}, ios: {}, assets: [], commands: {}};
const androidLinkConfig = require('../android');
const iosLinkConfig = require('../ios');
const config = {
getPlatformConfig: () => ({ios: { linkConfig: iosLinkConfig }, android: { linkConfig: androidLinkConfig }}),
getPlatformConfig: () => ({
ios: {linkConfig: iosLinkConfig},
android: {linkConfig: androidLinkConfig},
}),
getProjectConfig: () => ({android: {}, ios: {}, assets: []}),
getDependencyConfig: sinon.stub().returns(dependencyConfig),
};
jest.setMock(
'../android/isInstalled.js',
sinon.stub().returns(false)
);
jest.setMock('../android/isInstalled.js', sinon.stub().returns(false));
jest.setMock(
'../android/registerNativeModule.js',
registerNativeModule
);
jest.setMock('../android/registerNativeModule.js', registerNativeModule);
jest.setMock(
'../ios/isInstalled.js',
sinon.stub().returns(false)
);
jest.setMock('../ios/isInstalled.js', sinon.stub().returns(false));
jest.setMock(
'../ios/registerNativeModule.js',
registerNativeModule
);
jest.setMock('../ios/registerNativeModule.js', registerNativeModule);
const link = require('../link').func;
@ -115,34 +101,22 @@ describe('link', () => {
});
});
it('should not register modules when they are already installed', (done) => {
it('should not register modules when they are already installed', done => {
const registerNativeModule = sinon.stub();
const dependencyConfig = {ios: {}, android: {}, assets: [], commands: {}};
const config = {
getPlatformConfig: () => ({ios: {}, android: {}}),
getProjectConfig: () => ({ ios: {}, android: {}, assets: [] }),
getProjectConfig: () => ({ios: {}, android: {}, assets: []}),
getDependencyConfig: sinon.stub().returns(dependencyConfig),
};
jest.setMock(
'../ios/isInstalled.js',
sinon.stub().returns(true)
);
jest.setMock('../ios/isInstalled.js', sinon.stub().returns(true));
jest.setMock(
'../android/isInstalled.js',
sinon.stub().returns(true)
);
jest.setMock('../android/isInstalled.js', sinon.stub().returns(true));
jest.setMock(
'../ios/registerNativeModule.js',
registerNativeModule
);
jest.setMock('../ios/registerNativeModule.js', registerNativeModule);
jest.setMock(
'../android/registerNativeModule.js',
registerNativeModule
);
jest.setMock('../android/registerNativeModule.js', registerNativeModule);
const link = require('../link').func;
@ -152,25 +126,32 @@ describe('link', () => {
});
});
it('should register native modules for plugins', (done) => {
it('should register native modules for plugins', done => {
const registerNativeModule = sinon.stub();
const dependencyConfig = {ios: {}, android: {}, test: {}, assets: [], commands: {}};
const linkPluginConfig = { isInstalled: () => false, register: registerNativeModule };
const dependencyConfig = {
ios: {},
android: {},
test: {},
assets: [],
commands: {},
};
const linkPluginConfig = {
isInstalled: () => false,
register: registerNativeModule,
};
const config = {
getPlatformConfig: () => ({ ios: {}, android: {}, test: { linkConfig: () => linkPluginConfig }}),
getProjectConfig: () => ({ ios: {}, android: {}, test: {}, assets: [] }),
getPlatformConfig: () => ({
ios: {},
android: {},
test: {linkConfig: () => linkPluginConfig},
}),
getProjectConfig: () => ({ios: {}, android: {}, test: {}, assets: []}),
getDependencyConfig: sinon.stub().returns(dependencyConfig),
};
jest.setMock(
'../ios/isInstalled.js',
sinon.stub().returns(true)
);
jest.setMock('../ios/isInstalled.js', sinon.stub().returns(true));
jest.setMock(
'../android/isInstalled.js',
sinon.stub().returns(true)
);
jest.setMock('../android/isInstalled.js', sinon.stub().returns(true));
const link = require('../link').func;
@ -180,25 +161,32 @@ describe('link', () => {
});
});
it('should not register native modules for plugins when already installed', (done) => {
it('should not register native modules for plugins when already installed', done => {
const registerNativeModule = sinon.stub();
const dependencyConfig = {ios: {}, android: {}, test: {}, assets: [], commands: {}};
const linkPluginConfig = { isInstalled: () => true, register: registerNativeModule};
const dependencyConfig = {
ios: {},
android: {},
test: {},
assets: [],
commands: {},
};
const linkPluginConfig = {
isInstalled: () => true,
register: registerNativeModule,
};
const config = {
getPlatformConfig: () => ({ ios: {}, android: {}, test: { linkConfig: () => linkPluginConfig }}),
getProjectConfig: () => ({ ios: {}, android: {}, test: {}, assets: [] }),
getPlatformConfig: () => ({
ios: {},
android: {},
test: {linkConfig: () => linkPluginConfig},
}),
getProjectConfig: () => ({ios: {}, android: {}, test: {}, assets: []}),
getDependencyConfig: sinon.stub().returns(dependencyConfig),
};
jest.setMock(
'../ios/isInstalled.js',
sinon.stub().returns(true)
);
jest.setMock('../ios/isInstalled.js', sinon.stub().returns(true));
jest.setMock(
'../android/isInstalled.js',
sinon.stub().returns(true)
);
jest.setMock('../android/isInstalled.js', sinon.stub().returns(true));
const link = require('../link').func;
@ -208,27 +196,23 @@ describe('link', () => {
});
});
it('should run prelink and postlink commands at the appropriate times', (done) => {
it('should run prelink and postlink commands at the appropriate times', done => {
const registerNativeModule = sinon.stub();
const prelink = sinon.stub().yieldsAsync();
const postlink = sinon.stub().yieldsAsync();
jest.setMock(
'../ios/registerNativeModule.js',
registerNativeModule
);
jest.setMock('../ios/registerNativeModule.js', registerNativeModule);
jest.setMock(
'../ios/isInstalled.js',
sinon.stub().returns(false)
);
jest.setMock('../ios/isInstalled.js', sinon.stub().returns(false));
const linkConfig = require('../ios');
const config = {
getPlatformConfig: () => ({ ios: { linkConfig: linkConfig }}),
getProjectConfig: () => ({ ios: {}, assets: [] }),
getPlatformConfig: () => ({ios: {linkConfig: linkConfig}}),
getProjectConfig: () => ({ios: {}, assets: []}),
getDependencyConfig: sinon.stub().returns({
ios: {}, assets: [], commands: { prelink, postlink },
ios: {},
assets: [],
commands: {prelink, postlink},
}),
};
@ -241,21 +225,18 @@ describe('link', () => {
});
});
it('should copy assets from both project and dependencies projects', (done) => {
it('should copy assets from both project and dependencies projects', done => {
const dependencyAssets = ['Fonts/Font.ttf'];
const dependencyConfig = {assets: dependencyAssets, ios: {}, commands: {}};
const projectAssets = ['Fonts/FontC.ttf'];
const copyAssets = sinon.stub();
jest.setMock(
'../ios/copyAssets.js',
copyAssets
);
jest.setMock('../ios/copyAssets.js', copyAssets);
const linkConfig = require('../ios');
const config = {
getPlatformConfig: () => ({ ios: { linkConfig: linkConfig } }),
getProjectConfig: () => ({ ios: {}, assets: projectAssets }),
getPlatformConfig: () => ({ios: {linkConfig: linkConfig}}),
getProjectConfig: () => ({ios: {}, assets: projectAssets}),
getDependencyConfig: sinon.stub().returns(dependencyConfig),
};
@ -264,7 +245,7 @@ describe('link', () => {
link(['react-native-blur'], config).then(() => {
expect(copyAssets.calledOnce).toBeTruthy();
expect(copyAssets.getCall(0).args[0]).toEqual(
projectAssets.concat(dependencyAssets)
projectAssets.concat(dependencyAssets),
);
done();
});

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -19,21 +20,31 @@ const LINE_AFTER_TARGET_IN_TEST_PODFILE = 4;
describe('pods::findLineToAddPod', () => {
it('returns null if file is not Podfile', () => {
const podfile = readPodfile(path.join(PODFILES_PATH, '../Info.plist'));
expect(findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE)).toBeNull();
expect(
findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE),
).toBeNull();
});
it('returns correct line number for Simple Podfile', () => {
const podfile = readPodfile(path.join(PODFILES_PATH, 'PodfileSimple'));
expect(findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE)).toEqual({ line: 7, indentation: 2 });
expect(
findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE),
).toEqual({line: 7, indentation: 2});
});
it('returns correct line number for Podfile with target', () => {
const podfile = readPodfile(path.join(PODFILES_PATH, 'PodfileWithTarget'));
expect(findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE)).toEqual({ line: 21, indentation: 2 });
expect(
findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE),
).toEqual({line: 21, indentation: 2});
});
it('returns correct line number for Podfile with function', () => {
const podfile = readPodfile(path.join(PODFILES_PATH, 'PodfileWithFunction'));
expect(findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE)).toEqual({ line: 26, indentation: 2 });
const podfile = readPodfile(
path.join(PODFILES_PATH, 'PodfileWithFunction'),
);
expect(
findLineToAddPod(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE),
).toEqual({line: 26, indentation: 2});
});
});

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -24,12 +25,19 @@ describe('pods::findMarkedLinesInPodfile', () => {
it('returns empty array for Simple Podfile', () => {
const podfile = readPodfile(path.join(PODFILES_PATH, 'PodfileSimple'));
expect(findMarkedLinesInPodfile(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE)).toEqual([]);
expect(
findMarkedLinesInPodfile(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE),
).toEqual([]);
});
it('returns correct line numbers for Podfile with marker', () => {
const podfile = readPodfile(path.join(PODFILES_PATH, 'PodfileWithMarkers'));
const expectedObject = [{ line: 18, indentation: 2 }, { line: 31, indentation: 4 }];
expect(findMarkedLinesInPodfile(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE)).toEqual(expectedObject);
const expectedObject = [
{line: 18, indentation: 2},
{line: 31, indentation: 4},
];
expect(
findMarkedLinesInPodfile(podfile, LINE_AFTER_TARGET_IN_TEST_PODFILE),
).toEqual(expectedObject);
});
});

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -16,26 +17,26 @@ const PODFILES_PATH = path.join(__dirname, '../../__fixtures__/pods');
describe('pods::isInstalled', () => {
it('returns false if pod is missing', () => {
const project = { podfile: path.join(PODFILES_PATH, 'PodfileSimple') };
const podspecName = { podspec: 'NotExisting' };
const project = {podfile: path.join(PODFILES_PATH, 'PodfileSimple')};
const podspecName = {podspec: 'NotExisting'};
expect(isInstalled(project, podspecName)).toBe(false);
});
it('returns true for existing pod with version number', () => {
const project = { podfile: path.join(PODFILES_PATH, 'PodfileSimple') };
const podspecName = { podspec: 'TestPod' };
const project = {podfile: path.join(PODFILES_PATH, 'PodfileSimple')};
const podspecName = {podspec: 'TestPod'};
expect(isInstalled(project, podspecName)).toBe(true);
});
it('returns true for existing pod with path', () => {
const project = { podfile: path.join(PODFILES_PATH, 'PodfileWithTarget') };
const podspecName = { podspec: 'Yoga' };
const project = {podfile: path.join(PODFILES_PATH, 'PodfileWithTarget')};
const podspecName = {podspec: 'Yoga'};
expect(isInstalled(project, podspecName)).toBe(true);
});
it('returns true for existing pod with multiline definition', () => {
const project = { podfile: path.join(PODFILES_PATH, 'PodfileWithFunction') };
const podspecName = { podspec: 'React' };
const project = {podfile: path.join(PODFILES_PATH, 'PodfileWithFunction')};
const podspecName = {podspec: 'React'};
expect(isInstalled(project, podspecName)).toBe(true);
});
});

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -17,21 +18,25 @@ const PODFILES_PATH = path.join(__dirname, '../../__fixtures__/pods');
describe('pods::removePodEntry', () => {
it('should remove one line from Podfile with TestPod', () => {
const { podfileContent, podLinesCount } = readTestPodFile('PodfileSimple');
const {podfileContent, podLinesCount} = readTestPodFile('PodfileSimple');
const podFileWithRemoved = removePodEntry(podfileContent, 'TestPod');
const newLineCount = podFileWithRemoved.split('\n').length;
expect(newLineCount).toBe(podLinesCount - 1);
});
it('should remove one line from Podfile with Yoga', () => {
const { podfileContent, podLinesCount } = readTestPodFile('PodfileWithTarget');
const {podfileContent, podLinesCount} = readTestPodFile(
'PodfileWithTarget',
);
const podFileWithRemoved = removePodEntry(podfileContent, 'Yoga');
const newLineCount = podFileWithRemoved.split('\n').length;
expect(newLineCount).toBe(podLinesCount - 1);
});
it('should remove whole reference to React pod from Podfile', () => {
const { podfileContent, podLinesCount } = readTestPodFile('PodfileWithTarget');
const {podfileContent, podLinesCount} = readTestPodFile(
'PodfileWithTarget',
);
const podFileWithRemoved = removePodEntry(podfileContent, 'React');
const newLineCount = podFileWithRemoved.split('\n').length;
expect(newLineCount).toBe(podLinesCount - 9);
@ -40,5 +45,8 @@ describe('pods::removePodEntry', () => {
function readTestPodFile(fileName) {
const podfileLines = readPodfile(path.join(PODFILES_PATH, fileName));
return { podfileContent: podfileLines.join('\n'), podLinesCount: podfileLines.length };
return {
podfileContent: podfileLines.join('\n'),
podLinesCount: podfileLines.length,
};
}

View File

@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/
@ -13,8 +14,7 @@ const sinon = require('sinon');
const promiseWaterfall = require('../promiseWaterfall');
describe('promiseWaterfall', () => {
it('should run promises in a sequence', (done) => {
it('should run promises in a sequence', done => {
const tasks = [sinon.stub(), sinon.stub()];
promiseWaterfall(tasks).then(() => {
@ -23,7 +23,7 @@ describe('promiseWaterfall', () => {
});
});
it('should resolve with last promise value', (done) => {
it('should resolve with last promise value', done => {
const tasks = [sinon.stub().returns(1), sinon.stub().returns(2)];
promiseWaterfall(tasks).then(value => {
@ -32,7 +32,7 @@ describe('promiseWaterfall', () => {
});
});
it('should stop the sequence when one of promises is rejected', (done) => {
it('should stop the sequence when one of promises is rejected', done => {
const error = new Error();
const tasks = [sinon.stub().throws(error), sinon.stub().returns(2)];
@ -42,5 +42,4 @@ describe('promiseWaterfall', () => {
done();
});
});
});

View File

@ -3,6 +3,8 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
const fs = require('fs-extra');
@ -19,6 +21,9 @@ module.exports = function copyAssetsAndroid(files, project) {
const assets = groupFilesByType(files);
(assets.font || []).forEach(asset =>
fs.copySync(asset, path.join(project.assetsPath, 'fonts', path.basename(asset)))
fs.copySync(
asset,
path.join(project.assetsPath, 'fonts', path.basename(asset)),
),
);
};

View File

@ -3,13 +3,15 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
const fs = require('fs-extra');
exports.readFile = (file) =>
() => fs.readFileSync(file, 'utf8');
exports.readFile = file => () => fs.readFileSync(file, 'utf8');
exports.writeFile = (file, content) => content ?
fs.writeFileSync(file, content, 'utf8') :
(c) => fs.writeFileSync(file, c, 'utf8');
exports.writeFile = (file, content) =>
content
? fs.writeFileSync(file, content, 'utf8')
: c => fs.writeFileSync(file, c, 'utf8');

View File

@ -1,9 +1,11 @@
/** @format */
module.exports = function() {
return {
isInstalled: require('./isInstalled'),
register: require('./registerNativeModule'),
unregister: require('./unregisterNativeModule'),
copyAssets: require('./copyAssets'),
unlinkAssets: require('./unlinkAssets')
unlinkAssets: require('./unlinkAssets'),
};
};

View File

@ -3,6 +3,8 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
const fs = require('fs');

View File

@ -3,19 +3,16 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
const toCamelCase = require('lodash').camelCase;
module.exports = function applyParams(str, params, prefix) {
return str.replace(
/\$\{(\w+)\}/g,
(pattern, param) => {
return str.replace(/\$\{(\w+)\}/g, (pattern, param) => {
const name = toCamelCase(prefix) + '_' + param;
return params[param]
? `getResources().getString(R.string.${name})`
: null;
}
);
return params[param] ? `getResources().getString(R.string.${name})` : null;
});
};

View File

@ -3,13 +3,17 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
const fs = require('fs');
module.exports = function applyPatch(file, patch) {
fs.writeFileSync(file, fs
fs.writeFileSync(
file,
fs
.readFileSync(file, 'utf8')
.replace(patch.pattern, match => `${match}${patch.patch}`)
.replace(patch.pattern, match => `${match}${patch.patch}`),
);
};

View File

@ -3,6 +3,8 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
const normalizeProjectName = require('./normalizeProjectName');
@ -10,12 +12,12 @@ const normalizeProjectName = require('./normalizeProjectName');
module.exports = function makeBuildPatch(name) {
const normalizedProjectName = normalizeProjectName(name);
const installPattern = new RegExp(
`\\s{4}(compile)(\\(|\\s)(project)\\(\\\':${normalizedProjectName}\\\'\\)(\\)|\\s)`
`\\s{4}(compile)(\\(|\\s)(project)\\(\\\':${normalizedProjectName}\\\'\\)(\\)|\\s)`,
);
return {
installPattern,
pattern: /[^ \t]dependencies {\n/,
patch: ` compile project(':${normalizedProjectName}')\n`
patch: ` compile project(':${normalizedProjectName}')\n`,
};
};

View File

@ -3,6 +3,8 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
module.exports = function makeImportPatch(packageImportPath) {

View File

@ -3,6 +3,8 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
const applyParams = require('./applyParams');

View File

@ -3,6 +3,8 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
const path = require('path');
@ -10,14 +12,17 @@ const normalizeProjectName = require('./normalizeProjectName');
const isWin = process.platform === 'win32';
module.exports = function makeSettingsPatch(name, androidConfig, projectConfig) {
module.exports = function makeSettingsPatch(
name,
androidConfig,
projectConfig,
) {
var projectDir = path.relative(
path.dirname(projectConfig.settingsGradlePath),
androidConfig.sourceDir
androidConfig.sourceDir,
);
const normalizedProjectName = normalizeProjectName(name);
/*
* Fix for Windows
* Backslashes is the escape character and will result in
@ -30,7 +35,8 @@ module.exports = function makeSettingsPatch(name, androidConfig, projectConfig)
return {
pattern: '\n',
patch: `include ':${normalizedProjectName}'\n` +
patch:
`include ':${normalizedProjectName}'\n` +
`project(':${normalizedProjectName}').projectDir = ` +
`new File(rootProject.projectDir, '${projectDir}')\n`,
};

View File

@ -3,21 +3,22 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
const toCamelCase = require('lodash').camelCase;
module.exports = function makeStringsPatch(params, prefix) {
const values = Object.keys(params)
.map(param => {
const values = Object.keys(params).map(param => {
const name = toCamelCase(prefix) + '_' + param;
return ' ' +
`<string moduleConfig="true" name="${name}">${params[param]}</string>`;
return (
' ' +
`<string moduleConfig="true" name="${name}">${params[param]}</string>`
);
});
const patch = values.length > 0
? values.join('\n') + '\n'
: '';
const patch = values.length > 0 ? values.join('\n') + '\n' : '';
return {
pattern: '<resources>\n',

View File

@ -1,3 +1,4 @@
/** @format */
module.exports = function normalizeProjectName(name) {
return name.replace(/\//g, '_');

View File

@ -3,13 +3,15 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
const fs = require('fs');
module.exports = function revokePatch(file, patch) {
fs.writeFileSync(file, fs
.readFileSync(file, 'utf8')
.replace(patch.patch, '')
fs.writeFileSync(
file,
fs.readFileSync(file, 'utf8').replace(patch.patch, ''),
);
};

View File

@ -3,6 +3,8 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
const applyPatch = require('./patches/applyPatch');
@ -16,13 +18,13 @@ module.exports = function registerNativeAndroidModule(
name,
androidConfig,
params,
projectConfig
projectConfig,
) {
const buildPatch = makeBuildPatch(name);
applyPatch(
projectConfig.settingsGradlePath,
makeSettingsPatch(name, androidConfig, projectConfig)
makeSettingsPatch(name, androidConfig, projectConfig),
);
applyPatch(projectConfig.buildGradlePath, buildPatch);
@ -30,11 +32,11 @@ module.exports = function registerNativeAndroidModule(
applyPatch(
projectConfig.mainFilePath,
makePackagePatch(androidConfig.packageInstance, params, name)
makePackagePatch(androidConfig.packageInstance, params, name),
);
applyPatch(
projectConfig.mainFilePath,
makeImportPatch(androidConfig.packageImportPath)
makeImportPatch(androidConfig.packageImportPath),
);
};

Some files were not shown because too many files have changed in this diff Show More