--keep-prefix for JS generator (#5018)
authorGabriel Nützi <gnuetzi@gmail.com>
Fri, 2 Nov 2018 15:54:43 +0000 (16:54 +0100)
committerWouter van Oortmerssen <aardappel@gmail.com>
Fri, 2 Nov 2018 15:54:43 +0000 (08:54 -0700)
* keep include path

* add option --keep-prefix for js

* format contribution (format whole files before merge!)

* revert util.h : IsAbsPath ...

* JS Generator: only support relatives paths (keep it as it was)

src/idl_gen_js.cpp

index 8245dde..2986056 100644 (file)
@@ -128,8 +128,7 @@ class JsGenerator : public BaseGenerator {
       const auto basename =
           flatbuffers::StripPath(flatbuffers::StripExtension(file));
       if (basename != file_name_) {
-        const auto file_name = basename + kGeneratedFileNamePostfix;
-        code += GenPrefixedImport(file, file_name);
+        code += GenPrefixedImport(file, basename);
       }
     }
   }
@@ -524,10 +523,26 @@ class JsGenerator : public BaseGenerator {
     return "NS" + std::to_string(HashFnv1a<uint64_t>(file.c_str()));
   }
 
-  static std::string GenPrefixedImport(const std::string &full_file_name,
-                                       const std::string &base_file_name) {
+  std::string GenPrefixedImport(const std::string &full_file_name,
+                                const std::string &base_name) {
+    // Either keep the include path as it was
+    // or use only the base_name + kGeneratedFileNamePostfix
+    std::string path;
+    if (parser_.opts.keep_include_path) {
+      auto it = parser_.included_files_.find(full_file_name);
+      FLATBUFFERS_ASSERT(it != parser_.included_files_.end());
+      path =
+          flatbuffers::StripExtension(it->second) + kGeneratedFileNamePostfix;
+    } else {
+      path = base_name + kGeneratedFileNamePostfix;
+    }
+
+    // Add the include prefix and make the path always relative
+    path = flatbuffers::ConCatPathFileName(parser_.opts.include_prefix, path);
+    path = std::string(".") + kPathSeparator + path;
+
     return "import * as " + GenFileNamespacePrefix(full_file_name) +
-           " from \"./" + base_file_name + "\";\n";
+           " from \"" + path + "\";\n";
   }
 
   // Adds a source-dependent prefix, for of import * statements.