conversion.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. #! /usr/bin/env node
  2. 'use strict'
  3. const fs = require('fs');
  4. const path = require('path');
  5. const args = process.argv.slice(2);
  6. const dir = args[0];
  7. if (!dir) {
  8. console.log('Usage: node ' + path.basename(__filename) + ' <target-dir>');
  9. process.exit(1);
  10. }
  11. const NodeApiVersion = require('../package.json').version;
  12. const disable = args[1];
  13. if (disable != "--disable" && dir != "--disable") {
  14. var ConfigFileOperations = {
  15. 'package.json': [
  16. [ /([ ]*)"dependencies": {/g, '$1"dependencies": {\n$1 "node-addon-api": "' + NodeApiVersion + '",'],
  17. [ /[ ]*"nan": *"[^"]+"(,|)[\n\r]/g, '' ]
  18. ],
  19. 'binding.gyp': [
  20. [ /([ ]*)'include_dirs': \[/g, '$1\'include_dirs\': [\n$1 \'<!(node -p "require(\\\'node-addon-api\\\').include_dir")\',' ],
  21. [ /([ ]*)"include_dirs": \[/g, '$1"include_dirs": [\n$1 "<!(node -p \\"require(\'node-addon-api\').include_dir\\")",' ],
  22. [ /[ ]*("|')<!\(node -e ("|'|\\"|\\')require\(("|'|\\"|\\')nan("|'|\\"|\\')\)("|'|\\"|\\')\)("|')(,|)[\r\n]/g, '' ],
  23. [ /([ ]*)("|')target_name("|'): ("|')(.+?)("|'),/g, '$1$2target_name$2: $4$5$6,\n $2cflags!$2: [ $2-fno-exceptions$2 ],\n $2cflags_cc!$2: [ $2-fno-exceptions$2 ],\n $2xcode_settings$2: { $2GCC_ENABLE_CPP_EXCEPTIONS$2: $2YES$2,\n $2CLANG_CXX_LIBRARY$2: $2libc++$2,\n $2MACOSX_DEPLOYMENT_TARGET$2: $210.7$2,\n },\n $2msvs_settings$2: {\n $2VCCLCompilerTool$2: { $2ExceptionHandling$2: 1 },\n },' ],
  24. ]
  25. };
  26. } else {
  27. var ConfigFileOperations = {
  28. 'package.json': [
  29. [ /([ ]*)"dependencies": {/g, '$1"dependencies": {\n$1 "node-addon-api": "' + NodeApiVersion + '",'],
  30. [ /[ ]*"nan": *"[^"]+"(,|)[\n\r]/g, '' ]
  31. ],
  32. 'binding.gyp': [
  33. [ /([ ]*)'include_dirs': \[/g, '$1\'include_dirs\': [\n$1 \'<!(node -p "require(\\\'node-addon-api\\\').include_dir")\',' ],
  34. [ /([ ]*)"include_dirs": \[/g, '$1"include_dirs": [\n$1 "<!(node -p \'require(\\\"node-addon-api\\\").include_dir\')",' ],
  35. [ /[ ]*("|')<!\(node -e ("|'|\\"|\\')require\(("|'|\\"|\\')nan("|'|\\"|\\')\)("|'|\\"|\\')\)("|')(,|)[\r\n]/g, '' ],
  36. [ /([ ]*)("|')target_name("|'): ("|')(.+?)("|'),/g, '$1$2target_name$2: $4$5$6,\n $2cflags!$2: [ $2-fno-exceptions$2 ],\n $2cflags_cc!$2: [ $2-fno-exceptions$2 ],\n $2defines$2: [ $2NAPI_DISABLE_CPP_EXCEPTIONS$2 ],\n $2conditions$2: [\n [\'OS==\"win\"\', { $2defines$2: [ $2_HAS_EXCEPTIONS=1$2 ] }]\n ]' ],
  37. ]
  38. };
  39. }
  40. var SourceFileOperations = [
  41. [ /Nan::SetMethod\(target,[\s]*\"(.*)\"[\s]*,[\s]*([^)]+)\)/g, 'exports.Set(Napi::String::New(env, \"$1\"), Napi::Function::New(env, $2))' ],
  42. [ /v8::Local<v8::FunctionTemplate>\s+(\w+)\s*=\s*Nan::New<FunctionTemplate>\([\w\d:]+\);(?:\w+->Reset\(\1\))?\s+\1->SetClassName\(Nan::String::New\("(\w+)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$2", {' ],
  43. [ /Local<FunctionTemplate>\s+(\w+)\s*=\s*Nan::New<FunctionTemplate>\([\w\d:]+\);\s+(\w+)\.Reset\((\1)\);\s+\1->SetClassName\((Nan::String::New|Nan::New<(v8::)*String>)\("(.+?)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$6", {'],
  44. [ /Local<FunctionTemplate>\s+(\w+)\s*=\s*Nan::New<FunctionTemplate>\([\w\d:]+\);(?:\w+->Reset\(\1\))?\s+\1->SetClassName\(Nan::String::New\("(\w+)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$2", {' ],
  45. [ /Nan::New<v8::FunctionTemplate>\(([\w\d:]+)\)->GetFunction\(\)/g, 'Napi::Function::New(env, $1)' ],
  46. [ /Nan::New<FunctionTemplate>\(([\w\d:]+)\)->GetFunction()/g, 'Napi::Function::New(env, $1);' ],
  47. [ /Nan::New<v8::FunctionTemplate>\(([\w\d:]+)\)/g, 'Napi::Function::New(env, $1)' ],
  48. [ /Nan::New<FunctionTemplate>\(([\w\d:]+)\)/g, 'Napi::Function::New(env, $1)' ],
  49. // FunctionTemplate to FunctionReference
  50. [ /Nan::Persistent<(v8::)*FunctionTemplate>/g, 'Napi::FunctionReference' ],
  51. [ /Nan::Persistent<(v8::)*Function>/g, 'Napi::FunctionReference' ],
  52. [ /v8::Local<v8::FunctionTemplate>/g, 'Napi::FunctionReference' ],
  53. [ /Local<FunctionTemplate>/g, 'Napi::FunctionReference' ],
  54. [ /v8::FunctionTemplate/g, 'Napi::FunctionReference' ],
  55. [ /FunctionTemplate/g, 'Napi::FunctionReference' ],
  56. [ /([ ]*)Nan::SetPrototypeMethod\(\w+, "(\w+)", (\w+)\);/g, '$1InstanceMethod("$2", &$3),' ],
  57. [ /([ ]*)(?:\w+\.Reset\(\w+\);\s+)?\(target\)\.Set\("(\w+)",\s*Nan::GetFunction\((\w+)\)\);/gm,
  58. '});\n\n' +
  59. '$1constructor = Napi::Persistent($3);\n' +
  60. '$1constructor.SuppressDestruct();\n' +
  61. '$1target.Set("$2", $3);' ],
  62. // TODO: Other attribute combinations
  63. [ /static_cast<PropertyAttribute>\(ReadOnly\s*\|\s*DontDelete\)/gm,
  64. 'static_cast<napi_property_attributes>(napi_enumerable | napi_configurable)' ],
  65. [ /([\w\d:<>]+?)::Cast\((.+?)\)/g, '$2.As<$1>()' ],
  66. [ /\*Nan::Utf8String\(([^)]+)\)/g, '$1->As<Napi::String>().Utf8Value().c_str()' ],
  67. [ /Nan::Utf8String +(\w+)\(([^)]+)\)/g, 'std::string $1 = $2.As<Napi::String>()' ],
  68. [ /Nan::Utf8String/g, 'std::string' ],
  69. [ /v8::String::Utf8Value (.+?)\((.+?)\)/g, 'Napi::String $1(env, $2)' ],
  70. [ /String::Utf8Value (.+?)\((.+?)\)/g, 'Napi::String $1(env, $2)' ],
  71. [ /\.length\(\)/g, '.Length()' ],
  72. [ /Nan::MakeCallback\(([^,]+),[\s\\]+([^,]+),/gm, '$2.MakeCallback($1,' ],
  73. [ /class\s+(\w+)\s*:\s*public\s+Nan::ObjectWrap/g, 'class $1 : public Napi::ObjectWrap<$1>' ],
  74. [ /(\w+)\(([^\)]*)\)\s*:\s*Nan::ObjectWrap\(\)\s*(,)?/gm, '$1($2) : Napi::ObjectWrap<$1>()$3' ],
  75. // HandleOKCallback to OnOK
  76. [ /HandleOKCallback/g, 'OnOK' ],
  77. // HandleErrorCallback to OnError
  78. [ /HandleErrorCallback/g, 'OnError' ],
  79. // ex. .As<Function>() to .As<Napi::Object>()
  80. [ /\.As<v8::(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>\(\)/g, '.As<Napi::$1>()' ],
  81. [ /\.As<(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>\(\)/g, '.As<Napi::$1>()' ],
  82. // ex. Nan::New<Number>(info[0]) to Napi::Number::New(info[0])
  83. [ /Nan::New<(v8::)*Integer>\((.+?)\)/g, 'Napi::Number::New(env, $2)' ],
  84. [ /Nan::New\(([0-9\.]+)\)/g, 'Napi::Number::New(env, $1)' ],
  85. [ /Nan::New<(v8::)*String>\("(.+?)"\)/g, 'Napi::String::New(env, "$2")' ],
  86. [ /Nan::New\("(.+?)"\)/g, 'Napi::String::New(env, "$1")' ],
  87. [ /Nan::New<(v8::)*(.+?)>\(\)/g, 'Napi::$2::New(env)' ],
  88. [ /Nan::New<(.+?)>\(\)/g, 'Napi::$1::New(env)' ],
  89. [ /Nan::New<(v8::)*(.+?)>\(/g, 'Napi::$2::New(env, ' ],
  90. [ /Nan::New<(.+?)>\(/g, 'Napi::$1::New(env, ' ],
  91. [ /Nan::NewBuffer\(/g, 'Napi::Buffer<char>::New(env, ' ],
  92. // TODO: Properly handle this
  93. [ /Nan::New\(/g, 'Napi::New(env, ' ],
  94. [ /\.IsInt32\(\)/g, '.IsNumber()' ],
  95. [ /->IsInt32\(\)/g, '.IsNumber()' ],
  96. [ /(.+?)->BooleanValue\(\)/g, '$1.As<Napi::Boolean>().Value()' ],
  97. [ /(.+?)->Int32Value\(\)/g, '$1.As<Napi::Number>().Int32Value()' ],
  98. [ /(.+?)->Uint32Value\(\)/g, '$1.As<Napi::Number>().Uint32Value()' ],
  99. [ /(.+?)->IntegerValue\(\)/g, '$1.As<Napi::Number>().Int64Value()' ],
  100. [ /(.+?)->NumberValue\(\)/g, '$1.As<Napi::Number>().DoubleValue()' ],
  101. // ex. Nan::To<bool>(info[0]) to info[0].Value()
  102. [ /Nan::To<v8::(Boolean|String|Number|Object|Array|Symbol|Function)>\((.+?)\)/g, '$2.To<Napi::$1>()' ],
  103. [ /Nan::To<(Boolean|String|Number|Object|Array|Symbol|Function)>\((.+?)\)/g, '$2.To<Napi::$1>()' ],
  104. // ex. Nan::To<bool>(info[0]) to info[0].As<Napi::Boolean>().Value()
  105. [ /Nan::To<bool>\((.+?)\)/g, '$1.As<Napi::Boolean>().Value()' ],
  106. // ex. Nan::To<int>(info[0]) to info[0].As<Napi::Number>().Int32Value()
  107. [ /Nan::To<int>\((.+?)\)/g, '$1.As<Napi::Number>().Int32Value()' ],
  108. // ex. Nan::To<int32_t>(info[0]) to info[0].As<Napi::Number>().Int32Value()
  109. [ /Nan::To<int32_t>\((.+?)\)/g, '$1.As<Napi::Number>().Int32Value()' ],
  110. // ex. Nan::To<uint32_t>(info[0]) to info[0].As<Napi::Number>().Uint32Value()
  111. [ /Nan::To<uint32_t>\((.+?)\)/g, '$1.As<Napi::Number>().Uint32Value()' ],
  112. // ex. Nan::To<int64_t>(info[0]) to info[0].As<Napi::Number>().Int64Value()
  113. [ /Nan::To<int64_t>\((.+?)\)/g, '$1.As<Napi::Number>().Int64Value()' ],
  114. // ex. Nan::To<float>(info[0]) to info[0].As<Napi::Number>().FloatValue()
  115. [ /Nan::To<float>\((.+?)\)/g, '$1.As<Napi::Number>().FloatValue()' ],
  116. // ex. Nan::To<double>(info[0]) to info[0].As<Napi::Number>().DoubleValue()
  117. [ /Nan::To<double>\((.+?)\)/g, '$1.As<Napi::Number>().DoubleValue()' ],
  118. [ /Nan::New\((\w+)\)->HasInstance\((\w+)\)/g, '$2.InstanceOf($1.Value())' ],
  119. [ /Nan::Has\(([^,]+),\s*/gm, '($1).Has(' ],
  120. [ /\.Has\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\)/gm, '.Has($1)' ],
  121. [ /\.Has\([\s|\\]*Nan::New\(([^)]+)\)\)/gm, '.Has($1)' ],
  122. [ /Nan::Get\(([^,]+),\s*/gm, '($1).Get(' ],
  123. [ /\.Get\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\)/gm, '.Get($1)' ],
  124. [ /\.Get\([\s|\\]*Nan::New\(([^)]+)\)\)/gm, '.Get($1)' ],
  125. [ /Nan::Set\(([^,]+),\s*/gm, '($1).Set(' ],
  126. [ /\.Set\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\s*,/gm, '.Set($1,' ],
  127. [ /\.Set\([\s|\\]*Nan::New\(([^)]+)\)\s*,/gm, '.Set($1,' ],
  128. // ex. node::Buffer::HasInstance(info[0]) to info[0].IsBuffer()
  129. [ /node::Buffer::HasInstance\((.+?)\)/g, '$1.IsBuffer()' ],
  130. // ex. node::Buffer::Length(info[0]) to info[0].Length()
  131. [ /node::Buffer::Length\((.+?)\)/g, '$1.As<Napi::Buffer<char>>().Length()' ],
  132. // ex. node::Buffer::Data(info[0]) to info[0].Data()
  133. [ /node::Buffer::Data\((.+?)\)/g, '$1.As<Napi::Buffer<char>>().Data()' ],
  134. [ /Nan::CopyBuffer\(/g, 'Napi::Buffer::Copy(env, ' ],
  135. // Nan::AsyncQueueWorker(worker)
  136. [ /Nan::AsyncQueueWorker\((.+)\);/g, '$1.Queue();' ],
  137. [ /Nan::(Undefined|Null|True|False)\(\)/g, 'env.$1()' ],
  138. // Nan::ThrowError(error) to Napi::Error::New(env, error).ThrowAsJavaScriptException()
  139. [ /([ ]*)return Nan::Throw(\w*?)Error\((.+?)\);/g, '$1Napi::$2Error::New(env, $3).ThrowAsJavaScriptException();\n$1return env.Null();' ],
  140. [ /Nan::Throw(\w*?)Error\((.+?)\);\n(\s*)return;/g, 'Napi::$1Error::New(env, $2).ThrowAsJavaScriptException();\n$3return env.Null();' ],
  141. [ /Nan::Throw(\w*?)Error\((.+?)\);/g, 'Napi::$1Error::New(env, $2).ThrowAsJavaScriptException();\n' ],
  142. // Nan::RangeError(error) to Napi::RangeError::New(env, error)
  143. [ /Nan::(\w*?)Error\((.+)\)/g, 'Napi::$1Error::New(env, $2)' ],
  144. [ /Nan::Set\((.+?),\n* *(.+?),\n* *(.+?),\n* *(.+?)\)/g, '$1.Set($2, $3, $4)' ],
  145. [ /Nan::(Escapable)?HandleScope\s+(\w+)\s*;/g, 'Napi::$1HandleScope $2(env);' ],
  146. [ /Nan::(Escapable)?HandleScope/g, 'Napi::$1HandleScope' ],
  147. [ /Nan::ForceSet\(([^,]+), ?/g, '$1->DefineProperty(' ],
  148. [ /\.ForceSet\(Napi::String::New\(env, "(\w+)"\),\s*?/g, '.DefineProperty("$1", ' ],
  149. // [ /Nan::GetPropertyNames\(([^,]+)\)/, '$1->GetPropertyNames()' ],
  150. [ /Nan::Equals\(([^,]+),/g, '$1.StrictEquals(' ],
  151. [ /(.+)->Set\(/g, '$1.Set\(' ],
  152. [ /Nan::Callback/g, 'Napi::FunctionReference' ],
  153. [ /Nan::Persistent<Object>/g, 'Napi::ObjectReference' ],
  154. [ /Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target/g, 'Napi::Env& env, Napi::Object& target' ],
  155. [ /(\w+)\*\s+(\w+)\s*=\s*Nan::ObjectWrap::Unwrap<\w+>\(info\.This\(\)\);/g, '$1* $2 = this;' ],
  156. [ /Nan::ObjectWrap::Unwrap<(\w+)>\((.*)\);/g, '$2.Unwrap<$1>();' ],
  157. [ /Nan::NAN_METHOD_RETURN_TYPE/g, 'void' ],
  158. [ /NAN_INLINE/g, 'inline' ],
  159. [ /Nan::NAN_METHOD_ARGS_TYPE/g, 'const Napi::CallbackInfo&' ],
  160. [ /NAN_METHOD\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)'],
  161. [ /static\s*NAN_GETTER\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)' ],
  162. [ /NAN_GETTER\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)' ],
  163. [ /static\s*NAN_SETTER\(([\w\d:]+?)\)/g, 'void $1(const Napi::CallbackInfo& info, const Napi::Value& value)' ],
  164. [ /NAN_SETTER\(([\w\d:]+?)\)/g, 'void $1(const Napi::CallbackInfo& info, const Napi::Value& value)' ],
  165. [ /void Init\((v8::)*Local<(v8::)*Object> exports\)/g, 'Napi::Object Init(Napi::Env env, Napi::Object exports)' ],
  166. [ /NAN_MODULE_INIT\(([\w\d:]+?)\);/g, 'Napi::Object $1(Napi::Env env, Napi::Object exports);' ],
  167. [ /NAN_MODULE_INIT\(([\w\d:]+?)\)/g, 'Napi::Object $1(Napi::Env env, Napi::Object exports)' ],
  168. [ /::(Init(?:ialize)?)\(target\)/g, '::$1(env, target, module)' ],
  169. [ /constructor_template/g, 'constructor' ],
  170. [ /Nan::FunctionCallbackInfo<(v8::)?Value>[ ]*& [ ]*info\)[ ]*{\n*([ ]*)/gm, 'Napi::CallbackInfo& info) {\n$2Napi::Env env = info.Env();\n$2' ],
  171. [ /Nan::FunctionCallbackInfo<(v8::)*Value>\s*&\s*info\);/g, 'Napi::CallbackInfo& info);' ],
  172. [ /Nan::FunctionCallbackInfo<(v8::)*Value>\s*&/g, 'Napi::CallbackInfo&' ],
  173. [ /Buffer::HasInstance\(([^)]+)\)/g, '$1.IsBuffer()' ],
  174. [ /info\[(\d+)\]->/g, 'info[$1].' ],
  175. [ /info\[([\w\d]+)\]->/g, 'info[$1].' ],
  176. [ /info\.This\(\)->/g, 'info.This().' ],
  177. [ /->Is(Object|String|Int32|Number)\(\)/g, '.Is$1()' ],
  178. [ /info.GetReturnValue\(\).SetUndefined\(\)/g, 'return env.Undefined()' ],
  179. [ /info\.GetReturnValue\(\)\.Set\(((\n|.)+?)\);/g, 'return $1;' ],
  180. // ex. Local<Value> to Napi::Value
  181. [ /v8::Local<v8::(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>/g, 'Napi::$1' ],
  182. [ /Local<(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>/g, 'Napi::$1' ],
  183. // Declare an env in helper functions that take a Napi::Value
  184. [ /(\w+)\(Napi::Value (\w+)(,\s*[^\()]+)?\)\s*{\n*([ ]*)/gm, '$1(Napi::Value $2$3) {\n$4Napi::Env env = $2.Env();\n$4' ],
  185. // delete #include <node.h> and/or <v8.h>
  186. [ /#include +(<|")(?:node|nan).h("|>)/g, "#include $1napi.h$2\n#include $1uv.h$2" ],
  187. // NODE_MODULE to NODE_API_MODULE
  188. [ /NODE_MODULE/g, 'NODE_API_MODULE' ],
  189. [ /Nan::/g, 'Napi::' ],
  190. [ /nan.h/g, 'napi.h' ],
  191. // delete .FromJust()
  192. [ /\.FromJust\(\)/g, '' ],
  193. // delete .ToLocalCheck()
  194. [ /\.ToLocalChecked\(\)/g, '' ],
  195. [ /^.*->SetInternalFieldCount\(.*$/gm, '' ],
  196. // replace using node; and/or using v8; to using Napi;
  197. [ /using (node|v8);/g, 'using Napi;' ],
  198. [ /using namespace (node|Nan|v8);/g, 'using namespace Napi;' ],
  199. // delete using v8::Local;
  200. [ /using v8::Local;\n/g, '' ],
  201. // replace using v8::XXX; with using Napi::XXX
  202. [ /using v8::([A-Za-z]+);/g, 'using Napi::$1;' ],
  203. ];
  204. var paths = listFiles(dir);
  205. paths.forEach(function(dirEntry) {
  206. var filename = dirEntry.split('\\').pop().split('/').pop();
  207. // Check whether the file is a source file or a config file
  208. // then execute function accordingly
  209. var sourcePattern = /.+\.h|.+\.cc|.+\.cpp/;
  210. if (sourcePattern.test(filename)) {
  211. convertFile(dirEntry, SourceFileOperations);
  212. } else if (ConfigFileOperations[filename] != null) {
  213. convertFile(dirEntry, ConfigFileOperations[filename]);
  214. }
  215. });
  216. function listFiles(dir, filelist) {
  217. var files = fs.readdirSync(dir);
  218. filelist = filelist || [];
  219. files.forEach(function(file) {
  220. if (file === 'node_modules') {
  221. return
  222. }
  223. if (fs.statSync(path.join(dir, file)).isDirectory()) {
  224. filelist = listFiles(path.join(dir, file), filelist);
  225. } else {
  226. filelist.push(path.join(dir, file));
  227. }
  228. });
  229. return filelist;
  230. }
  231. function convert(content, operations) {
  232. for (let i = 0; i < operations.length; i ++) {
  233. let operation = operations[i];
  234. content = content.replace(operation[0], operation[1]);
  235. }
  236. return content;
  237. }
  238. function convertFile(fileName, operations) {
  239. fs.readFile(fileName, "utf-8", function (err, file) {
  240. if (err) throw err;
  241. file = convert(file, operations);
  242. fs.writeFile(fileName, file, function(err){
  243. if (err) throw err;
  244. });
  245. });
  246. }