← back to Secrets Manager

hero-image-fallback.py

42 lines

import re,json,sys,urllib.request
env=open('/Users/macstudio3/Projects/secrets-manager/.env').read()
tok=re.search(r'^SHOPIFY_THEME_TOKEN=(.+)$',env,re.M).group(1).strip().strip('"').strip("'")
S="designer-laboratory-sandbox.myshopify.com";A="2024-10";TID=144396058675;KEY="sections/dw-collection-hero.liquid"
APPLY='--apply' in sys.argv
def g():
    r=urllib.request.Request(f"https://{S}/admin/api/{A}/themes/{TID}/assets.json?asset[key]={KEY}",headers={"X-Shopify-Access-Token":tok})
    return json.load(urllib.request.urlopen(r,timeout=30))['asset']['value']
def p(v):
    b=json.dumps({"asset":{"key":KEY,"value":v}}).encode()
    r=urllib.request.Request(f"https://{S}/admin/api/{A}/themes/{TID}/assets.json",data=b,method="PUT",headers={"X-Shopify-Access-Token":tok,"Content-Type":"application/json"})
    return json.load(urllib.request.urlopen(r,timeout=30))
v=g()
old_block="""{%- liquid
  assign dw_has_hero = false
  if collection.image
    assign dw_has_hero = true
  endif
-%}"""
new_block="""{%- liquid
  assign dw_hero_img = collection.image
  unless dw_hero_img
    assign dw_hero_img = collection.products.first.featured_image
  endunless
  assign dw_has_hero = false
  if dw_hero_img
    assign dw_has_hero = true
  endif
-%}"""
old_bg="{% if dw_has_hero %}style=\"background-image:url({{ collection.image | img_url: '2048x' }});\"{% endif %}"
new_bg="{% if dw_has_hero %}style=\"background-image:url({{ dw_hero_img | img_url: '2048x' }});\"{% endif %}"
if 'dw_hero_img' in v:
    print("fallback already applied — no change"); sys.exit(0)
reps=[(old_block,new_block),(old_bg,new_bg)]
miss=[o[:40] for o,_ in reps if o not in v]
if miss: print("target(s) not found:",miss); sys.exit(1)
if not APPLY:
    print("DRY: 2 edits located ✓ — hero falls back to first product image (fixes 85 gaps)"); sys.exit(0)
nv=v
for o,n in reps: nv=nv.replace(o,n,1)
print("PUT:", "OK" if 'asset' in p(nv) else "FAIL")