Allow NOSORT to be the last line in a comment in addition to the first.

I found it surprising that

  # Don't sort these because $whatever:
  # NOSORT
  ...

didn't work and that I had to do

  # NOSORT
  # Don't sort these because $whatever:
  ...

Support both forms.

Bug: none
Change-Id: I72db3fb37e792bd7db31668252b1c280425d7049
Reviewed-on: https://gn-review.googlesource.com/c/3560
Reviewed-by: Petr Hosek <phosek@google.com>
Commit-Queue: Petr Hosek <phosek@google.com>
diff --git a/tools/gn/command_format.cc b/tools/gn/command_format.cc
index d656dd8..483a24c 100644
--- a/tools/gn/command_format.cc
+++ b/tools/gn/command_format.cc
@@ -328,11 +328,15 @@
 }
 
 void Printer::SortIfSourcesOrDeps(const BinaryOpNode* binop) {
-  if (binop->comments() && !binop->comments()->before().empty() &&
-      binop->comments()->before()[0].value().as_string() == "# NOSORT") {
-    // Allow disabling of sort for specific actions that might be
-    // order-sensitive.
-    return;
+  if (const Comments* comments = binop->comments()) {
+    const std::vector<Token>& before = comments->before();
+    if (!before.empty() &&
+        (before.front().value().as_string() == "# NOSORT" ||
+         before.back().value().as_string() == "# NOSORT")) {
+      // Allow disabling of sort for specific actions that might be
+      // order-sensitive.
+      return;
+    }
   }
   const IdentifierNode* ident = binop->left()->AsIdentifier();
   const ListNode* list = binop->right()->AsList();
diff --git a/tools/gn/format_test_data/066.gn b/tools/gn/format_test_data/066.gn
index c62eb2a..0a79d0c 100644
--- a/tools/gn/format_test_data/066.gn
+++ b/tools/gn/format_test_data/066.gn
@@ -14,6 +14,7 @@
 ]
 
 # NOSORT
+# This is NOSORT because reason.
 sources = [
   "z",
   "z2",
@@ -21,6 +22,7 @@
   "y.cc",
 ]
 
+# This is NOSORT because reason:
 # NOSORT
 sources += [
   "z",
diff --git a/tools/gn/format_test_data/066.golden b/tools/gn/format_test_data/066.golden
index 45467b8..9b7bb5c 100644
--- a/tools/gn/format_test_data/066.golden
+++ b/tools/gn/format_test_data/066.golden
@@ -12,6 +12,7 @@
 sources += [ "a" ]
 
 # NOSORT
+# This is NOSORT because reason.
 sources = [
   "z",
   "z2",
@@ -19,6 +20,7 @@
   "y.cc",
 ]
 
+# This is NOSORT because reason:
 # NOSORT
 sources += [
   "z",