(ui, path)
| 9 | * @throws {Error} If GitHub settings are missing or fetch fails. |
| 10 | */ |
| 11 | export async function loadPostFromGitHub(ui, path) { |
| 12 | const { ghOwnerInput: owner, ghRepoInput: repo, ghTokenInput: token } = ui; |
| 13 | if (!owner.value || !repo.value || !token.value) { |
| 14 | throw new Error('Please fill in GitHub settings first.'); |
| 15 | } |
| 16 | |
| 17 | const cleanPath = path.startsWith('./') ? path.substring(2) : path; |
| 18 | try { |
| 19 | const file = await ghFetch(ui, `/contents/${cleanPath}`); |
| 20 | const content = fromBase64(file.content); |
| 21 | const sha = file.sha; |
| 22 | |
| 23 | const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/); |
| 24 | if (!match) { |
| 25 | return { content, sha, path: cleanPath }; |
| 26 | } |
| 27 | |
| 28 | const frontMatter = match[1]; |
| 29 | const body = match[2]; |
| 30 | const data = {}; |
| 31 | frontMatter.split('\n').forEach((line) => { |
| 32 | const colonIndex = line.indexOf(':'); |
| 33 | if (colonIndex === -1) { |
| 34 | return; |
| 35 | } |
| 36 | const key = line.substring(0, colonIndex).trim(); |
| 37 | let value = line.substring(colonIndex + 1).trim(); |
| 38 | if (value.startsWith('"') && value.endsWith('"')) { |
| 39 | value = value.substring(1, value.length - 1); |
| 40 | } |
| 41 | if (value.startsWith('[') && value.endsWith(']')) { |
| 42 | value = value |
| 43 | .substring(1, value.length - 1) |
| 44 | .split(',') |
| 45 | .map((t) => t.trim().replace(/^["']|["']$/g, '')); |
| 46 | } |
| 47 | data[key] = value; |
| 48 | }); |
| 49 | |
| 50 | const dirPath = cleanPath.substring(0, cleanPath.lastIndexOf('/')); |
| 51 | const images = []; |
| 52 | try { |
| 53 | const dirContents = await ghFetch(ui, `/contents/${dirPath}`); |
| 54 | const imageFiles = dirContents.filter( |
| 55 | (f) => f.type === 'file' && /\.(jpe?g|png|gif|webp|svg)$/i.test(f.name), |
| 56 | ); |
| 57 | for (const imgFile of imageFiles) { |
| 58 | const imgData = await ghFetch(ui, `/contents/${imgFile.path}`); |
| 59 | images.push({ |
| 60 | name: imgFile.name, |
| 61 | sha: imgFile.sha, |
| 62 | content: imgData.content, |
| 63 | path: imgFile.path, |
| 64 | }); |
| 65 | } |
| 66 | } catch (e) { |
| 67 | console.warn('Could not fetch images', e); |
| 68 | } |
no test coverage detected