From 67cf26cbbd998ad9ebc85e7fe47c875f7d226f38 Mon Sep 17 00:00:00 2001
From: Geoff Shannon <geoffpshannon@gmail.com>
Date: Sat, 16 May 2015 12:39:31 -0500
Subject: [PATCH] Don't open a file as root if it is owned by the current user

Fixes #839.

The reasoning behind this is that if we own a file, we can change it's
permissions with `chmod` so there's probably a good reason it's not
writable.
---
 core/prelude-core.el | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)

diff --git a/core/prelude-core.el b/core/prelude-core.el
index 5243eb8..30db174 100644
--- a/core/prelude-core.el
+++ b/core/prelude-core.el
@@ -285,6 +285,17 @@ there's a region, all lines that region covers will be duplicated."
   (interactive)
   (byte-recompile-directory prelude-dir 0))
 
+(defun prelude-file-owner-uid (filename)
+  "Return the UID of the FILENAME as an integer.
+
+See `file-attributes' for more info."
+  (nth 2 (file-attributes filename 'integer)))
+
+(defun prelude-file-owned-by-user-p (filename)
+  "Return t if file FILENAME is owned by the currently logged in user."
+  (equal (prelude-file-owner-uid filename)
+         (user-uid)))
+
 (defun prelude-find-alternate-file-as-root (filename)
   "Wraps `find-alternate-file' with opening a file as root."
   (find-alternate-file (concat "/sudo:root@localhost:" filename)))
@@ -307,7 +318,8 @@ buffer is not visiting a file."
   (unless (or (tramp-tramp-file-p buffer-file-name)
               (equal major-mode 'dired-mode)
               (not (file-exists-p (file-name-directory buffer-file-name)))
-              (file-writable-p buffer-file-name))
+              (file-writable-p buffer-file-name)
+              (prelude-file-owned-by-user-p buffer-file-name))
     (prelude-find-alternate-file-as-root buffer-file-name)))
 (add-hook 'find-file-hook 'prelude-reopen-as-root)