Snap for 5656475 from f840ab08799b36d1f95726fc2b24b3a4612b380c to qt-release

Change-Id: I84147691e9b2282791640ba3b2f29d5f3f393e73
diff --git a/aidl_unittest.cpp b/aidl_unittest.cpp
index 8c4d796..3c5c641 100644
--- a/aidl_unittest.cpp
+++ b/aidl_unittest.cpp
@@ -1323,5 +1323,39 @@
   EXPECT_NE(0, ::android::aidl::compile_aidl(options, io_delegate_));
 }
 
+class AidlOutputPathTest : public AidlTest {
+ protected:
+  void SetUp() override {
+    AidlTest::SetUp();
+    io_delegate_.SetFileContents("sub/dir/foo/bar/IFoo.aidl", "package foo.bar; interface IFoo {}");
+  }
+
+  void Test(const Options& options, const std::string expected_output_path) {
+    EXPECT_EQ(0, ::android::aidl::compile_aidl(options, io_delegate_));
+    // check the existence
+    EXPECT_TRUE(io_delegate_.GetWrittenContents(expected_output_path, nullptr));
+  }
+};
+
+TEST_F(AidlOutputPathTest, OutDirWithNoOutputFile) {
+  // <out_dir> / <package_name> / <type_name>.java
+  Test(Options::From("aidl -o out sub/dir/foo/bar/IFoo.aidl"), "out/foo/bar/IFoo.java");
+}
+
+TEST_F(AidlOutputPathTest, OutDirWithOutputFile) {
+  // when output file is explicitly set, it is always respected. -o option is
+  // ignored.
+  Test(Options::From("aidl -o out sub/dir/foo/bar/IFoo.aidl output/IFoo.java"), "output/IFoo.java");
+}
+
+TEST_F(AidlOutputPathTest, NoOutDirWithOutputFile) {
+  Test(Options::From("aidl -o out sub/dir/foo/bar/IFoo.aidl output/IFoo.java"), "output/IFoo.java");
+}
+
+TEST_F(AidlOutputPathTest, NoOutDirWithNoOutputFile) {
+  // output is the same as the input file except for the suffix
+  Test(Options::From("aidl sub/dir/foo/bar/IFoo.aidl"), "sub/dir/foo/bar/IFoo.java");
+}
+
 }  // namespace aidl
 }  // namespace android
diff --git a/options.cpp b/options.cpp
index 351b4f6..ff99dad 100644
--- a/options.cpp
+++ b/options.cpp
@@ -309,18 +309,17 @@
       input_files_.emplace_back(argv[optind++]);
       if (argc - optind >= 1) {
         output_file_ = argv[optind++];
-      } else {
-        // when output is omitted, output is by default set to the input
-        // file path with .aidl is replaced to .java.
+      } else if (output_dir_.empty()) {
+        // when output is omitted and -o option isn't set, the output is by
+        // default set to the input file path with .aidl is replaced to .java.
+        // If -o option is set, the output path is calculated by
+        // generate_outputFileName which returns "<output_dir>/<package/name>/
+        // <typename>.java"
         output_file_ = input_files_.front();
         if (android::base::EndsWith(output_file_, ".aidl")) {
           output_file_ = output_file_.substr(0, output_file_.length() - strlen(".aidl"));
         }
         output_file_ += ".java";
-
-        if (!output_dir_.empty()) {
-          output_file_ = output_dir_ + output_file_;
-        }
       }
     } else if (IsCppOutput()) {
       input_files_.emplace_back(argv[optind++]);