Skip to content

Instantly share code, notes, and snippets.

@SolveSoul
Created November 20, 2018 08:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SolveSoul/2049d8dc08c003ff27c9e550e9f7f8ba to your computer and use it in GitHub Desktop.
Save SolveSoul/2049d8dc08c003ff27c9e550e9f7f8ba to your computer and use it in GitHub Desktop.
This gist is based upon the answer @ https://stackoverflow.com/a/44440258/4614197 but also checks packages recursively
#!/usr/bin/env node
/*
* A hook to add resources class (R.java) import to Android classes which uses it.
* See: https://stackoverflow.com/a/44440258/4614197
*/
function getRegexGroupMatches(string, regex, index) {
index || (index = 1);
var matches = [];
var match;
if (regex.global) {
while (match = regex.exec(string)) {
matches.push(match[index]);
console.log('Match:', match);
}
}
else {
if (match = regex.exec(string)) {
matches.push(match[index]);
}
}
return matches;
}
module.exports = function (ctx) {
// If Android platform is not installed, don't even execute
if (ctx.opts.cordova.platforms.indexOf('android') < 0)
return;
var fs = ctx.requireCordovaModule('fs'),
path = ctx.requireCordovaModule('path'),
Q = ctx.requireCordovaModule('q'),
glob = ctx.requireCordovaModule('glob');
var deferral = Q.defer();
var platformSourcesRoot = path.join(ctx.opts.projectRoot, 'platforms/android/src');
var pluginSourcesRoot = path.join(ctx.opts.plugin.dir, 'src/android');
var androidPluginsData = JSON.parse(fs.readFileSync(path.join(ctx.opts.projectRoot, 'plugins', 'android.json'), 'utf8'));
var appPackage = androidPluginsData.installed_plugins[ctx.opts.plugin.id]['PACKAGE_NAME'];
console.log('Found plugin sources root', pluginSourcesRoot);
glob(pluginSourcesRoot + '/**/*.java', { absolute: true }, function (err, files) {
if (err) {
console.error('Error when reading file:', err);
deferral.reject();
return;
}
var deferrals = [];
//files.filter(function (file) { return path.extname(file) === '.java'; })
files.forEach(function (file) {
var deferral = Q.defer();
var filename = path.basename(file);
console.log('Checking file for R references', file);
fs.readFile(file, 'utf-8', function (err, contents) {
if (err) {
console.error('Error when reading file:', err);
deferral.reject();
return;
}
if (contents.match(/[^\.\w]R\./)) {
console.log('Trying to get packages from file:', filename);
var packages = getRegexGroupMatches(contents, /package ([^;]+);/);
for (var p = 0; p < packages.length; p++) {
try {
var package = packages[p];
var sourceFile = path.join(platformSourcesRoot, package.replace(/\./g, '/'), filename);
if (!fs.existsSync(sourceFile))
throw 'Can\'t find file in installed platform directory: "' + sourceFile + '".';
var sourceFileContents = fs.readFileSync(sourceFile, 'utf8');
if (!sourceFileContents)
throw 'Can\'t read file contents.';
var newContents = sourceFileContents
.replace(/(import ([^;]+).R;)/g, '')
.replace(/(package ([^;]+);)/g, '$1 import ' + appPackage + '.R;');
fs.writeFileSync(sourceFile, newContents, 'utf8');
break;
} catch (ex) {
console.log('Could not add import to "' + filename + '" using package "' + package + '". ' + ex);
}
}
}
});
deferrals.push(deferral.promise);
});
Q.all(deferrals)
.then(function() {
console.log('Done with the hook!');
deferral.resolve();
})
});
return deferral.promise;
}
@kuwabataK
Copy link

Hi,
Thank you for the very useful script. but in my environment, following error was occur

$ cordova plugin add sampleplugin
...
Could not add import to "NewActivity.java" using package "com.example.sample.plugin". Can't find file in installed platform directory: "/cordova-plugin-test/platforms/android/src/com/example/sample/plugin/NewActivity.java".

So, I fix following code and worked fine

var platformSourcesRoot = path.join(ctx.opts.projectRoot, 'platforms/android/src');

to

var platformSourcesRoot = path.join(ctx.opts.projectRoot, 'platforms/android/app/src/main/java');

this error is my environment-specific ? or common ones ?

my cordova version is following

$ cordova --version
8.1.2 (cordova-lib@8.1.1)

Sorry my English is broken and thank you read my comments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment