Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 46 additions & 6 deletions .clj-kondo/config.edn
Original file line number Diff line number Diff line change
@@ -1,11 +1,46 @@
{:linters {:shadowed-fn-param {:level :off}
{:output {:exclude-files [".*resources/public/js/compiled.*"
".*docker/scripts/.*"]}
:linters {:shadowed-fn-param {:level :off}
:shadowed-var {:level :off}
:if {:level :off}
:unused-namespace {:level :off}
:unused-binding {:level :off}
:missing-else-branch {:level :warning}
:clojure-lsp/unused-public-var
{:exclude [user ; REPL utilities
orcpub.styles.core/app
;; LSP can't trace cross-file references to these —
;; all are called from classes.cljc (live code)
orcpub.dnd.e5.options/monk-elemental-disciplines
orcpub.dnd.e5.options/spell-tags
orcpub.dnd.e5.options/potent-spellcasting
;; Live callers exist but LSP can't trace them
orcpub.common/dissoc-in ; events.cljs
orcpub.dnd.e5.character/add-ability-namespaces ; test
;; Cross-file refs: used in template.cljc but defined in spell_subs.cljs
orcpub.dnd.e5.spell-subs/sunlight-sensitivity
orcpub.dnd.e5.spell-subs/mask-of-the-wild-mod]
;; re-frame event handlers are dispatched via keyword, not var reference.
;; LSP can't connect reg-event-db registration to (dispatch [:keyword]).
:exclude-when-defined-by #{re-frame.core/reg-event-db
re-frame.core/reg-event-fx
re-frame.core/reg-sub
re-frame.core/reg-sub-raw}}
;; garden.selectors vars are generated by macros (defselector,
;; defpseudoclass, gen-pseudo-class-defs, etc.) at compile time.
;; clj-kondo can't resolve macro-generated vars statically and
;; garden doesn't ship a clj-kondo config.
:unresolved-var
{:exclude [garden.selectors
;; errors.cljc macros behind #?(:clj) reader conditional —
;; one kondo instance can't resolve them
orcpub.errors]}
;; read-string is a valid cljs.core symbol that clj-kondo
;; doesn't recognize in its ClojureScript analysis data.
:unresolved-symbol
{:exclude
[(clojure.core.match/match)
[read-string
(clojure.test.check.clojure-test/defspec)
(clojure.core.match/match)
(cljs.core.match/match)
(io.pedestal.interceptor.error/error-dispatch)
(orcpub.modifiers/modifier)
Expand All @@ -29,6 +64,11 @@
(orcpub.dnd.e5.modifiers/reaction)
(orcpub.dnd.e5.modifiers/level-val)
(orcpub.entity-spec/make-entity)
(orcpub.routes-test/with-conn)]}}
:lint-as {reagent.core/with-let clojure.core/let
hiccup.def/defhtml clojure.core/defn}}
(orcpub.routes-test/with-conn)
(orcpub.routes.folder-test/with-conn)
(user/with-db)]}}
:lint-as {reagent.core/with-let clojure.core/let
hiccup.def/defhtml clojure.core/defn
user/with-db clojure.core/let
clojure.test.check.clojure-test/defspec clojure.test/deftest}
}
93 changes: 93 additions & 0 deletions scripts/fix-missing-else.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
"""
Fix clj-kondo 'Missing else branch' warnings by replacing:
if -> when
if-let -> when-let
if-not -> when-not

Reads kondo output from stdin, applies fixes to source files.
Usage: lein lint 2>&1 | grep 'Missing else branch' | python3 scripts/fix-missing-else.py
"""

import sys
import re
from collections import defaultdict

def parse_warnings(lines):
"""Parse kondo output into {file: [(line, col), ...]} sorted by line desc."""
by_file = defaultdict(list)
for line in lines:
# Format: src/clj/foo.clj:42:3: warning: Missing else branch.
m = re.match(r'^(.+?):(\d+):(\d+):', line.strip())
if m:
by_file[m.group(1)].append((int(m.group(2)), int(m.group(3))))
# Sort each file's locations by line descending (process bottom-up to avoid offset shifts)
for f in by_file:
by_file[f].sort(reverse=True)
return by_file

def fix_at(source_line, col):
"""Replace if/if-let/if-not with when/when-let/when-not at the given column (1-based)."""
idx = col - 1 # convert to 0-based

# kondo column points to '(' — the 'if' token starts at idx+1
if source_line[idx:idx+1] == '(':
idx += 1

rest = source_line[idx:]

if rest.startswith('if-let'):
return source_line[:idx] + 'when-let' + source_line[idx + 6:]
elif rest.startswith('if-not'):
return source_line[:idx] + 'when-not' + source_line[idx + 6:]
elif rest.startswith('if-some'):
return source_line[:idx] + 'when-some' + source_line[idx + 7:]
elif rest.startswith('if-first'):
return source_line[:idx] + 'when-first' + source_line[idx + 8:]
elif rest.startswith('if'):
# Make sure it's standalone 'if', not 'if-' something else
after = source_line[idx + 2:idx + 3] if len(source_line) > idx + 2 else ''
if after in (' ', '\t', '\n', ''):
return source_line[:idx] + 'when' + source_line[idx + 2:]
else:
print(f" SKIP: unexpected token at col {col}: {rest[:20]}", file=sys.stderr)
return source_line
else:
print(f" SKIP: no if at col {col}: {rest[:20]}", file=sys.stderr)
return source_line

def main():
warnings = parse_warnings(sys.stdin)
total_fixed = 0
total_skipped = 0

for filepath, locations in sorted(warnings.items()):
with open(filepath, 'r') as f:
lines = f.readlines()

fixed = 0
for line_num, col in locations:
if line_num > len(lines):
print(f" SKIP: {filepath}:{line_num} beyond file length", file=sys.stderr)
total_skipped += 1
continue

old = lines[line_num - 1]
new = fix_at(old, col)
if old != new:
lines[line_num - 1] = new
fixed += 1
else:
total_skipped += 1

if fixed > 0:
with open(filepath, 'w') as f:
f.writelines(lines)

total_fixed += fixed
print(f" {filepath}: {fixed} fixed" + (f", {len(locations) - fixed} skipped" if len(locations) > fixed else ""))

print(f"\nTotal: {total_fixed} fixed, {total_skipped} skipped")

if __name__ == '__main__':
main()
2 changes: 1 addition & 1 deletion src/clj/orcpub/email.clj
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@
(str base-url (routes/path-for routes/reset-password-page-route) "?key=" reset-key))}))

(defn send-error-email [context exception]
(if (not-empty (environ/env :email-errors-to))
(when (not-empty (environ/env :email-errors-to))
(postal/send-message (email-cfg)
{:from (str "OrcPub Errors <" (emailfrom) ">")
:to (str (environ/env :email-errors-to))
Expand Down
2 changes: 1 addition & 1 deletion src/clj/orcpub/index.clj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
(def devmode? (env :dev-mode))

(defn meta-tag [property content]
(if content
(when content
[:meta
{:property property
:content content}]))
Expand Down
26 changes: 13 additions & 13 deletions src/clj/orcpub/pdf.clj
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
(let [field (.getField form (name k))]
(when field

(if (and flatten (font-sizes k) (instance? PDTextField field))
(when (and flatten (font-sizes k) (instance? PDTextField field))
(.setDefaultAppearance field (str "/Helv " " " (font-sizes k) " Tf 0 0 0 rg"))
;; this prints out weird boxes
#_(.setDefaultAppearance field (str COSName/DA "/" (.getName font-name) " " (font-sizes k 8) " Tf 0 0 0 rg")))
Expand Down Expand Up @@ -132,7 +132,7 @@
current-line nil
[next-word & remaining-words :as current-words] words]
(if next-word
(let [line-with-word (str current-line (if current-line " ") next-word)
(let [line-with-word (str current-line (when current-line " ") next-word)
new-width (string-width line-with-word font font-size)]
(if (> new-width width)
(recur (conj lines current-line)
Expand Down Expand Up @@ -169,16 +169,16 @@
(.setNonStrokingColor cs r g b))

(defn draw-text [cs text font font-size x y & [color]]
(if text
(when text
(let [units-x (* 72 x)
units-y (* 72 y)]
(.beginText cs)
(.setFont cs font font-size)
(if color
(when color
(apply set-text-color cs color))
(.moveTextPositionByAmount cs units-x units-y)
(.drawString cs (if (keyword? text) (common/safe-name text) text))
(if color
(when color
(set-text-color cs 0 0 0))
(.endText cs))))

Expand Down Expand Up @@ -253,7 +253,7 @@
(subs s 0 len)))

(defn abbreviate-duration [duration]
(if duration
(when duration
(-> duration
(s/replace #"Concentration,? up to " "Conc, ")
abbreviate-times
Expand Down Expand Up @@ -352,7 +352,7 @@
(for [j (range num-boxes-y)
i (range (dec num-boxes-x) -1 -1)
:let [spell-index (+ i (* j num-boxes-x))]]
(if-let [{:keys [class-nm dc attack-bonus spell] :as spell-data}
(when-let [{:keys [class-nm dc attack-bonus spell] :as spell-data}
(get (vec spells) spell-index)]
(let [{:keys [description
casting-time
Expand Down Expand Up @@ -385,7 +385,7 @@
(- 11.0 y 1.08) ;from the top down
(- box-width 0.24)
(- box-height 1.13))]
(if (:material-component components)
(when (:material-component components)
(draw-text-to-box cs
(str (s/capitalize (:material-component components)))
(:italic fonts)
Expand Down Expand Up @@ -426,7 +426,7 @@
(- 11.0 y 0.19)
(- box-width 0.24)
0.25)
(if casting-time
(when casting-time
(draw-spell-field cs
document
"magic-swirl"
Expand All @@ -437,7 +437,7 @@
#","))))
(+ x 0.12)
(- 11.0 y 0.45)))
(if range
(when range
(draw-spell-field cs
document
"arrow-dunk"
Expand All @@ -453,21 +453,21 @@
nil?
(map
(fn [[k v]]
(if (-> spell :components k)
(when (-> spell :components k)
v))
{:verbal "V"
:somatic "S"
:material "M"})))
(+ x 1.12)
(- 11.0 y 0.45))
(if duration
(when duration
(draw-spell-field cs
document
"sands-of-time"
(abbreviate-duration duration)
(+ x 1.62)
(- 11.0 y 0.45)))
(if (seq remaining-desc-lines)
(when (seq remaining-desc-lines)
(draw-imagex cs
over-img
(+ x 2.3)
Expand Down
2 changes: 1 addition & 1 deletion src/clj/orcpub/pedestal.clj
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
{body :body
{last-modified "Last-Modified"
content-length "Content-Length"} :headers} response
old-etag (if if-none-match
old-etag (when if-none-match
(-> if-none-match (s/split #"--gzip") first))
new-etag (or (parse-date last-modified content-length) (calculate-etag body))
not-modified? (and old-etag (= new-etag old-etag))]
Expand Down
2 changes: 1 addition & 1 deletion src/clj/orcpub/privacy.clj
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
:font-size 32
:paragraphs
["We may change this policy from time to time, and if we do we'll post any changes on this page. If you continue to use OrcPub after those changes are in effect, you agree to the revised policy. If the changes are significant, we may provide more prominent notice or get your consent as required by law."]}
(if (not (s/blank? (environ/env :email-access-key)))
(when (not (s/blank? (environ/env :email-access-key)))
{:title "How can you contact us?"
:font-size 32
:paragraphs
Expand Down
16 changes: 8 additions & 8 deletions src/clj/orcpub/routes.clj
Original file line number Diff line number Diff line change
Expand Up @@ -282,9 +282,9 @@

(defn register [{:keys [json-params db conn] :as request}]
(let [{:keys [username email password send-updates?]} json-params
username (if username (s/trim username))
email (if email (s/lower-case (s/trim email)))
password (if password (s/trim password))
username (when username (s/trim username))
email (when email (s/lower-case (s/trim email)))
password (when password (s/trim password))
validation (registration/validate-registration
json-params
(seq (d/q email-query db email))
Expand Down Expand Up @@ -496,18 +496,18 @@

(with-open [doc (PDDocument/load input)]
(pdf/write-fields! doc fields (not chrome?) font-sizes)
(if (and print-spell-cards? (seq spells-known))
(when (and print-spell-cards? (seq spells-known))
(add-spell-cards! doc spells-known spell-save-dcs spell-attack-mods custom-spells print-spell-card-dc-mod?))

(if (and image-url
(when (and image-url
(re-matches #"^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]" image-url)
(not image-url-failed))
(case print-character-sheet-style?
1 (pdf/draw-image! doc (pdf/get-page doc 1) image-url 0.45 1.75 2.35 3.15)
2 (pdf/draw-image! doc (pdf/get-page doc 1) image-url 0.45 1.75 2.35 3.15)
3 (pdf/draw-image! doc (pdf/get-page doc 1) image-url 0.45 1.75 2.35 3.15)
4 (pdf/draw-image! doc (pdf/get-page doc 0) image-url 0.50 0.85 2.35 3.15)))
(if (and faction-image-url
(when (and faction-image-url
(re-matches #"^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]" faction-image-url)
(not faction-image-url-failed))
(case print-character-sheet-style?
Expand Down Expand Up @@ -899,9 +899,9 @@
(defn character-summary-description [{:keys [::char5e/race-name ::char5e/subrace-name ::char5e/classes]}]
(str race-name
" "
(if subrace-name (str "(" subrace-name ") "))
(when subrace-name (str "(" subrace-name ") "))
" "
(if (seq classes)
(when (seq classes)
(s/join
" / "
(map
Expand Down
Loading
Loading