From c6272e4103b1ee4084c2b4ae4ce8a2c72f0d8764 Mon Sep 17 00:00:00 2001
From: Martin Green <martin.speleo@gmail.com>
Date: Mon, 20 Jun 2022 22:09:10 +0100
Subject: [PATCH] Refactorise saving code.  Do not save and git change if there
 are no changes

---
 core/views/expo.py | 84 +++++++++++++++++++++++++++-------------------
 1 file changed, 50 insertions(+), 34 deletions(-)

diff --git a/core/views/expo.py b/core/views/expo.py
index 18d21a3..33a905a 100644
--- a/core/views/expo.py
+++ b/core/views/expo.py
@@ -325,40 +325,12 @@ def editexpopage(request, path):
             body = body.replace("\r", "")
             result = "%s<head%s>%s</head>%s<body%s>\n%s</body>%s" % (preheader, headerargs, head, postheader, bodyargs, body, postbody)
             
-            cwd = filepath.parent
-            filename = filepath.name
-            git = settings.GIT
-            # GIT see also core/models/cave.py writetrogglefile()
-            # GIT see also core/views/uploads.py dwgupload()
-            try:
-                with open(os.path.normpath(filepath).encode(sysdefaultencoding), "w", encoding="utf8") as f:
-                    print(f'WRITING{cwd}---{filename} ')
-                    # as the wsgi process www-data, we have group write-access but are not owner, so cannot chmod.
-                    # os.chmod(filepath, 0o664) # set file permissions to rw-rw-r--
-                    f.write(result)
-            except PermissionError:
-                message = f'CANNOT  save this file.\nPERMISSIONS incorrectly set on server for this file {filename}. Ask a nerd to fix this.'
-                return render(request,'errors/generic.html', {'message': message})
-
-            try:
-                encoded_filename = filename.encode(sysdefaultencoding)
-                cp_add = subprocess.run([git, "add", encoded_filename], cwd=cwd, capture_output=True, text=True)
-                if cp_add.returncode != 0:
-                    msgdata = 'Ask a nerd to fix this.\n\n' + cp_add.stderr + '\n\n' + cp_add.stdout  + '\n\nreturn code: ' + str(cp_add.returncode)
-                    message = f'CANNOT git on server for this file {filename}. Edits saved but not added to git.\n\n' + msgdata
-                    return render(request,'errors/generic.html', {'message': message})
-               
-                cp_commit = subprocess.run([git, "commit", "-m", f'Troggle online: Edit this page - {encoded_filename}'], cwd=cwd, capture_output=True, text=True)
-                # This produces return code = 1 if it commits OK, but when the repo still needs to be pushed to origin/expoweb
-                if cp_commit.returncode != 0 and cp_commit.stdout != 'nothing to commit, working tree clean':
-                    msgdata = 'Ask a nerd to fix this.\n\n' + cp_commit.stderr + '\n\n' + cp_commit.stdout  + '\n\nreturn code: ' + str(cp_commit.returncode)
-                    message = f'Error code with git on server for this file {filename}. Edits saved, added to git, but NOT committed.\n\n' + msgdata
-                    return render(request,'errors/generic.html', {'message': message})
-
-            except subprocess.SubprocessError:
-                message = f'CANNOT git on server for this file {filename}. Subprocess error. Edits not saved.\nAsk a nerd to fix this.'
-                return render(request,'errors/generic.html', {'message': message})
- 
+            if result != html: # Check if content changed
+                try:
+                    write_and_commit(filepath, content)
+                except WriteAndCommitError as e:
+                    return render(request,'errors/generic.html', {'message': e.message})
+                
             return HttpResponseRedirect(reverse('expopage', args=[path])) # Redirect after POST
     else:
         if filefound:
@@ -373,6 +345,50 @@ def editexpopage(request, path):
             pageform = ExpoPageForm({"html": body, "title": "Missing"})
     return render(request, 'editexpopage.html', {'path': path, 'form': pageform, })
 
+class WriteAndCommitError(Exception):
+
+    def __init__(self, message):
+        self.message = message
+
+    def __str__(self):
+        return f'WriteAndCommitError: {self.message}'
+
+def write_and_commit(filepath, content):
+            cwd = filepath.parent
+            filename = filepath.name
+            git = settings.GIT
+            # GIT see also core/models/cave.py writetrogglefile()
+            # GIT see also core/views/uploads.py dwgupload()
+            
+            try:
+                with open(os.path.normpath(filepath).encode(sysdefaultencoding), "w", encoding="utf8") as f:
+                    print(f'WRITING{cwd}---{filename} ')
+                    # as the wsgi process www-data, we have group write-access but are not owner, so cannot chmod.
+                    # os.chmod(filepath, 0o664) # set file permissions to rw-rw-r--
+                    f.write(content)
+            except PermissionError:
+                message = f'CANNOT  save this file.\nPERMISSIONS incorrectly set on server for this file {filename}. Ask a nerd to fix this.'
+                raise WriteAndCommitError(message)
+
+            try:
+                encoded_filename = filename.encode(sysdefaultencoding)
+                cp_add = subprocess.run([git, "add", encoded_filename], cwd=cwd, capture_output=True, text=True)
+                if cp_add.returncode != 0:
+                    msgdata = 'Ask a nerd to fix this.\n\n' + cp_add.stderr + '\n\n' + cp_add.stdout  + '\n\nreturn code: ' + str(cp_add.returncode)
+                    message = f'CANNOT git on server for this file {filename}. Edits saved but not added to git.\n\n' + msgdata
+                    raise WriteAndCommitError(message)
+               
+                cp_commit = subprocess.run([git, "commit", "-m", f'Troggle online: Edit this page - {encoded_filename}'], cwd=cwd, capture_output=True, text=True)
+                # This produces return code = 1 if it commits OK, but when the repo still needs to be pushed to origin/expoweb
+                if cp_commit.returncode != 0 and cp_commit.stdout != 'nothing to commit, working tree clean':
+                    msgdata = 'Ask a nerd to fix this.\n\n' + cp_commit.stderr + '\n\n' + cp_commit.stdout  + '\n\nreturn code: ' + str(cp_commit.returncode)
+                    message = f'Error code with git on server for this file {filename}. Edits saved, added to git, but NOT committed.\n\n' + msgdata
+                    raise WriteAndCommitError(message)
+
+            except subprocess.SubprocessError:
+                message = f'CANNOT git on server for this file {filename}. Subprocess error. Edits not saved.\nAsk a nerd to fix this.'
+                raise WriteAndCommitError(message)
+
 class ExpoPageForm(forms.Form):
     '''The form used by the editexpopage function
     '''