store-listing-csv.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. #!/usr/bin/env python3
  2. """Fills Partner Center's exported Store-listing CSV with LYNX's listings in every language (round 165n).
  3. Usage: scripts/store-listing-csv.py <exported.csv> <output folder>
  4. 1. Partner Center › LYNX SHARE › app overview › Store listings › **Export listing** → a .csv (UTF-8) whose Field / ID /
  5. Type columns must stay as they are (the IDs are Partner Center's).
  6. 2. This script writes <output folder>/listings.csv (the same rows, a column per language from store/listings/*.md,
  7. the shared fields from store/listings/common.md in the "default" column) and copies the screenshots and logos into
  8. <output folder>/, with the paths Partner Center expects ("<folder name>/screenshots/01-workspace.png").
  9. 3. Partner Center › **Import listings** › **Import folder** → choose <output folder>.
  10. Field names in the export are matched loosely (case and punctuation ignored, a few known aliases); everything that
  11. could not be placed is listed at the end, so a renamed field shows up instead of being silently dropped.
  12. """
  13. import csv
  14. import os
  15. import re
  16. import shutil
  17. import sys
  18. ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  19. LISTINGS = os.path.join(ROOT, "store", "listings")
  20. # extra listing languages that reuse another file's text
  21. REUSE = {"es-mx": "es-es"}
  22. LIMITS = {"Description": 10000, "ReleaseNotes": 1500, "ShortDescription": 500, "Title": 256,
  23. "Feature": 200, "SearchTerm": 30, "Caption": 200}
  24. def norm(name):
  25. return re.sub(r"[^a-z0-9]", "", name.lower())
  26. def is_cjk(ch):
  27. return ord(ch) >= 0x2E80
  28. def unwrap(lines):
  29. """Hard-wrapped Markdown paragraphs → Store text: a paragraph is one line, bullets ("•", "- ") start new lines,
  30. blank lines stay paragraph breaks. CJK lines are joined without a space."""
  31. out = []
  32. for raw in lines:
  33. line = raw.rstrip()
  34. if not line:
  35. if out and out[-1] != "":
  36. out.append("")
  37. continue
  38. starts_item = line.lstrip().startswith(("•", "- ", "* ")) or re.match(r"^\s*\d+\.\s", line)
  39. if out and out[-1] != "" and not starts_item:
  40. prev = out[-1]
  41. joiner = "" if (prev and is_cjk(prev[-1])) or is_cjk(line.lstrip()[0]) else " "
  42. out[-1] = prev + joiner + line.strip()
  43. else:
  44. out.append(line.strip())
  45. while out and out[-1] == "":
  46. out.pop()
  47. return "\n".join(out)
  48. def sections(path):
  49. """'## Heading' → list of body lines (HTML comments removed)."""
  50. with open(path, encoding="utf-8") as f:
  51. text = re.sub(r"<!--.*?-->", "", f.read(), flags=re.S)
  52. result, current = {}, None
  53. for line in text.splitlines():
  54. m = re.match(r"^##\s+(.+?)\s*$", line)
  55. if m:
  56. current = m.group(1)
  57. result[current] = []
  58. elif current is not None:
  59. result[current].append(line)
  60. return result
  61. def items(lines):
  62. """Numbered or bulleted list items, one per line."""
  63. out = []
  64. for line in lines:
  65. m = re.match(r"^\s*(?:\d+\.|[-*•])\s+(.*\S)\s*$", line)
  66. if m:
  67. out.append(m.group(1))
  68. return out
  69. def language_fields(path):
  70. """{logical field: text} for one language file."""
  71. s = sections(path)
  72. fields = {}
  73. simple = {"Title": "Title", "Short description": "ShortDescription", "Description": "Description",
  74. "What's new": "ReleaseNotes"}
  75. for heading, field in simple.items():
  76. if heading in s:
  77. fields[field] = unwrap(s[heading])
  78. for i, text in enumerate(items(s.get("Features", [])), 1):
  79. fields[f"Feature{i}"] = text
  80. for i, text in enumerate(items(s.get("Search terms", [])), 1):
  81. fields[f"SearchTerm{i}"] = text
  82. for i, text in enumerate(items(s.get("Screenshot captions", [])), 1):
  83. # "01-workspace.png — caption"
  84. fields[f"Caption{i}"] = re.split(r"\s+[—–-]\s+", text, maxsplit=1)[-1]
  85. return fields
  86. def candidates(field):
  87. m = re.match(r"^([A-Za-z]+?)(\d+)$", field)
  88. if field.startswith("Caption") and m:
  89. n = m.group(2)
  90. return [f"desktopscreenshotcaption{n}", f"desktopscreenshot{n}caption", f"screenshotcaption{n}",
  91. f"caption{n}"]
  92. if field.startswith("Screenshot") and m:
  93. return [f"desktopscreenshot{m.group(2)}", f"screenshot{m.group(2)}"]
  94. aliases = {"ReleaseNotes": ["releasenotes", "whatsnew"], "PrivacyPolicy": ["privacypolicy", "privacypolicyurl"],
  95. "WebsiteURL": ["websiteurl", "website"], "SupportContactInfo": ["supportcontactinfo", "supportcontact"],
  96. "DevStudio": ["devstudio", "developedby"],
  97. "CopyrightTrademarkInfo": ["copyrighttrademarkinfo", "copyrighttrademarkinformation"]}
  98. return aliases.get(field, [norm(field)])
  99. def check_limit(lang, field, text, problems):
  100. key = re.sub(r"\d+$", "", field)
  101. limit = LIMITS.get(key)
  102. if limit and len(text) > limit:
  103. problems.append(f"{lang}: {field} has {len(text)} characters (limit {limit})")
  104. def main(argv):
  105. if len(argv) != 2:
  106. print(__doc__)
  107. return 2
  108. exported, out = argv
  109. with open(exported, encoding="utf-8-sig", newline="") as f:
  110. rows = list(csv.reader(f))
  111. # Partner Center has exported the third header both as "Type" and as "Type (Type)"
  112. if not rows or [c.strip().lower().split(" (")[0] for c in rows[0][:4]] != ["field", "id", "type", "default"]:
  113. raise SystemExit("not a Partner Center listing export (first columns must be Field, ID, Type, default)")
  114. header = rows[0]
  115. index = {}
  116. for r, row in enumerate(rows[1:], 1):
  117. if row:
  118. index.setdefault(norm(row[0]), r)
  119. folder = os.path.basename(os.path.normpath(out))
  120. os.makedirs(os.path.join(out, "screenshots"), exist_ok=True)
  121. problems, unplaced = [], []
  122. def put(field, column, text):
  123. for c in candidates(field):
  124. if c in index:
  125. row = rows[index[c]]
  126. while len(row) <= column:
  127. row.append("")
  128. row[column] = text
  129. return True
  130. unplaced.append(field)
  131. return False
  132. # default column: shared fields, screenshots and logos
  133. common = sections(os.path.join(LISTINGS, "common.md"))
  134. for heading, lines in common.items():
  135. if heading == "Screenshots":
  136. for i, name in enumerate([l.strip() for l in lines if l.strip()], 1):
  137. shutil.copy2(os.path.join(ROOT, "store", "screenshots", name), os.path.join(out, "screenshots", name))
  138. put(f"Screenshot{i}", 3, f"{folder}/screenshots/{name}")
  139. elif heading.startswith("StoreLogo"):
  140. name = unwrap(lines)
  141. shutil.copy2(os.path.join(ROOT, "store", name), os.path.join(out, name))
  142. put(heading, 3, f"{folder}/{name}")
  143. else:
  144. put(heading, 3, unwrap(lines))
  145. # one column per language file
  146. langs = sorted(f[:-3] for f in os.listdir(LISTINGS) if f.endswith(".md") and f != "common.md")
  147. # an extra language goes in only when the export has its column: importing a column the submission lacks fails
  148. langs += sorted(extra for extra, source in REUSE.items() if source in langs and extra not in langs and extra in [h.strip().lower() for h in header])
  149. for lang in langs:
  150. if lang in [h.strip().lower() for h in header]:
  151. column = [h.strip().lower() for h in header].index(lang)
  152. else:
  153. header.append(lang)
  154. column = len(header) - 1
  155. for field, text in language_fields(os.path.join(LISTINGS, REUSE.get(lang, lang) + ".md")).items():
  156. check_limit(lang, field, text, problems)
  157. put(field, column, text)
  158. width = len(header)
  159. for row in rows:
  160. row.extend([""] * (width - len(row)))
  161. with open(os.path.join(out, "listings.csv"), "w", encoding="utf-8", newline="") as f:
  162. csv.writer(f).writerows(rows)
  163. print(f"{out}/listings.csv: {len(langs)} languages ({', '.join(langs)})")
  164. for p in problems:
  165. print("TOO LONG:", p)
  166. for field in sorted(set(unplaced)):
  167. print("NOT IN THE EXPORT (fill by hand or rename the section):", field)
  168. return 1 if problems else 0
  169. if __name__ == "__main__":
  170. sys.exit(main(sys.argv[1:]))