From 2803a7fb99eda58e39b2cb891fecd45498d0b508 Mon Sep 17 00:00:00 2001
From: Frediano Ziglio <frediano.ziglio@cloud.com>
Date: Mon, 18 Dec 2023 10:36:01 +0000
Subject: [PATCH] Do not check for writable device if we don't need it

If justLooking is true we are just going to close and open
the device again (even on errors opening) so there won't be
visible changes however opening the device for writing will
cause Linux to attempt reloading partitions even if we aren't
changing anything.

Signed-off-by: Frediano Ziglio <frediano.ziglio@cloud.com>
---
 gpt.cc | 32 +++++++++++++++++---------------
 1 file changed, 17 insertions(+), 15 deletions(-)

diff --git a/gpt.cc b/gpt.cc
index 24d6918..7b42c3c 100644
--- a/gpt.cc
+++ b/gpt.cc
@@ -834,25 +834,27 @@ int GPTData::LoadPartitions(const string & deviceFilename) {
    int err, allOK = 1;
    MBRValidity mbrState;
 
-   if (myDisk.OpenForRead(deviceFilename)) {
-      err = myDisk.OpenForWrite(deviceFilename);
-      if ((err == 0) && (!justLooking)) {
-         cout << "\aNOTE: Write test failed with error number " << errno
-              << ". It will be impossible to save\nchanges to this disk's partition table!\n";
+   if (!justLooking) {
+      if (myDisk.OpenForRead(deviceFilename)) {
+         err = myDisk.OpenForWrite(deviceFilename);
+         if (err == 0) {
+            cout << "\aNOTE: Write test failed with error number " << errno
+                 << ". It will be impossible to save\nchanges to this disk's partition table!\n";
 #if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
-         cout << "You may be able to enable writes by exiting this program, typing\n"
-              << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
-              << "program.\n";
+            cout << "You may be able to enable writes by exiting this program, typing\n"
+                 << "'sysctl kern.geom.debugflags=16' at a shell prompt, and re-running this\n"
+                 << "program.\n";
 #endif
 #if defined (__APPLE__)
-         cout << "You may need to deactivate System Integrity Protection to use this program. See\n"
-              << "https://www.quora.com/How-do-I-turn-off-the-rootless-in-OS-X-El-Capitan-10-11\n"
-              << "for more information.\n";
+            cout << "You may need to deactivate System Integrity Protection to use this program. See\n"
+                 << "https://www.quora.com/How-do-I-turn-off-the-rootless-in-OS-X-El-Capitan-10-11\n"
+                 << "for more information.\n";
 #endif
-              cout << "\n";
-      } // if
-      myDisk.Close(); // Close and re-open read-only in case of bugs
-   } else allOK = 0; // if
+                 cout << "\n";
+         } // if
+         myDisk.Close(); // Close and re-open read-only in case of bugs
+      } else allOK = 0; // if
+   }
 
    if (allOK && myDisk.OpenForRead(deviceFilename)) {
       // store disk information....
-- 
2.49.0

