diff --git a/CHANGELOG.md b/CHANGELOG.md index 79220105..4dd5e8a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +* [#142](https://github.com/clojure-emacs/refactor-nrepl/issues/142): Guard `read-ns-form` against non-existing files. + ## 3.3.1 * [#363](https://github.com/clojure-emacs/refactor-nrepl/issues/363): Fix a memoization bug in `clean-namespace`. diff --git a/src/refactor_nrepl/core.clj b/src/refactor_nrepl/core.clj index 03cd1539..1c049206 100644 --- a/src/refactor_nrepl/core.clj +++ b/src/refactor_nrepl/core.clj @@ -155,25 +155,29 @@ (let [^String path-string (when (string? path) path) ^File path-file (when-not path-string - path)] - (with-open [file-reader (or (some-> path-string FileReader.) - (some-> path-file FileReader.))] - (try - (parse/read-ns-decl (readers/indexing-push-back-reader - (PushbackReader. file-reader))) - (catch Exception _ nil))))) + path) + ^File file (or path-file (File. path-string))] + ;; Check for file existence, because clj-refactor.el or other clients might have bugs: + (when (some-> file .exists) + (with-open [file-reader (FileReader. file)] + (try + (parse/read-ns-decl (readers/indexing-push-back-reader + (PushbackReader. file-reader))) + (catch Exception _ nil)))))) ([dialect path] (let [^String path-string (when (string? path) path) ^File path-file (when-not path-string - path)] - (with-open [file-reader (or (some-> path-string FileReader.) - (some-> path-file FileReader.))] - (try - (parse/read-ns-decl (readers/indexing-push-back-reader - (PushbackReader. file-reader)) - {:read-cond :allow :features #{dialect}}) - (catch Exception _ nil)))))) + path) + ^File file (or path-file (File. path-string))] + ;; Check for file existence, because clj-refactor.el or other clients might have bugs: + (when (some-> file .exists) + (with-open [file-reader (FileReader. file)] + (try + (parse/read-ns-decl (readers/indexing-push-back-reader + (PushbackReader. file-reader)) + {:read-cond :allow :features #{dialect}}) + (catch Exception _ nil))))))) (defn cljc-extension? [^String path] (.endsWith path ".cljc")) diff --git a/test/refactor_nrepl/core_test.clj b/test/refactor_nrepl/core_test.clj index c8bd552b..8ea30b34 100644 --- a/test/refactor_nrepl/core_test.clj +++ b/test/refactor_nrepl/core_test.clj @@ -30,10 +30,13 @@ (deftest test-read-ns-form (are [input expected] (testing input - (assert (-> input File. .exists)) + (case input + "alkjafas/does_not_exist.clj" (assert (not (-> input File. .exists))) + (assert (-> input File. .exists))) (is (= expected (sut/read-ns-form input))) true) + "alkjafas/does_not_exist.clj" nil "test-resources/readable_file_incorrect_aliases.clj" nil "testproject/src/com/example/one.clj" '(ns com.example.one (:require [com.example.two :as two :refer [foo]]