Skip to content

Commit 873ea24

Browse files
authored
fix(push-to-ipfs): manual request for ipfs push (#12)
1 parent ad94cf0 commit 873ea24

File tree

3 files changed

+61
-63
lines changed

3 files changed

+61
-63
lines changed

push-to-ipfs/action.yaml

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,36 @@ description: Push directory to IPFS
33

44
inputs:
55
upload-dir:
6-
description: 'Directory to upload'
6+
description: "Directory to upload"
77
required: true
88

99
runs:
10-
using: 'composite'
10+
using: "composite"
1111
steps:
12+
- name: Set up Python
13+
uses: actions/setup-python@v5
14+
with:
15+
python-version: 3.11
16+
17+
- name: Install dependencies
18+
run: |
19+
pip install -r ${{ github.action_path }}/scripts/requirements.txt
20+
shell: bash
21+
1222
- name: Push to IPFS
1323
id: push_to_ipfs
1424
shell: bash
1525
run: |
16-
pip install 'aioipfs>=0.6.2'
17-
CID=$(python3 ${{ github.action_path }}/scripts/push_on_ipfs.py "${{ github.workspace }}/${{ inputs.upload-dir }}")
18-
echo "CID: $CID" >> $GITHUB_STEP_SUMMARY
19-
echo "cid=$CID" >> $GITHUB_OUTPUT
26+
result=$(python3 ${{ github.action_path }}/scripts/push_on_ipfs.py "${{ github.workspace }}/${{ inputs.upload-dir }}")
27+
echo "CID V0: $(echo $result | jq -r '.cid_v0')" >> $GITHUB_STEP_SUMMARY
28+
echo "CID V1: $(echo $result | jq -r '.cid_v1')" >> $GITHUB_STEP_SUMMARY
29+
echo "cid_v0=$(echo $result | jq -r '.cid_v0')" >> $GITHUB_OUTPUT
30+
echo "cid_v1=$(echo $result | jq -r '.cid_v1')" >> $GITHUB_OUTPUT
31+
2032
outputs:
21-
cid:
22-
description: 'IPFS CID'
23-
value: ${{ steps.push_to_ipfs.outputs.cid }}
33+
cid_v0:
34+
description: "IPFS CID V0"
35+
value: ${{ steps.push_to_ipfs.outputs.cid_v0 }}
36+
cid_v1:
37+
description: "IPFS CID V0"
38+
value: ${{ steps.push_to_ipfs.outputs.cid_v1 }}

push-to-ipfs/scripts/push_on_ipfs.py

Lines changed: 35 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,65 +1,46 @@
11
#!/usr/bin/env python3
2-
3-
"""
4-
This script uploads the build SPA to IPFS.
5-
It does not ping it or do anything else yet, so the result can only be accessed
6-
as long as the files are not garbage collected.
7-
Requires: 'aioipfs>=0.6.2'
8-
"""
9-
10-
import asyncio
11-
import logging
2+
import requests
3+
import json
124
import sys
135
from pathlib import Path
14-
from typing import NewType
15-
16-
import aioipfs
17-
18-
logger = logging.getLogger(__file__)
19-
20-
Multiaddr = NewType("Multiaddr", str)
21-
CID = NewType("CID", str)
22-
6+
from cid import make_cid
7+
8+
def upload_with_requests(folder: Path, gateway: str):
9+
url = f"{gateway}/api/v0/add"
10+
params = {
11+
"recursive": "true",
12+
"wrap-with-directory": "true"
13+
}
14+
15+
# Prepare file data like curl -F file=@./dist/
16+
files = []
17+
for path in folder.rglob("*"):
18+
if path.is_file():
19+
relative_path = path.relative_to(folder.parent)
20+
files.append(
21+
("file", (str(relative_path), open(path, "rb")))
22+
)
2323

24-
def raise_no_cid():
25-
raise ValueError("Could not obtain a CID")
24+
response = requests.post(url, params=params, files=files)
25+
response.raise_for_status()
2626

27+
# Parse the response line-by-line
28+
cid_v0 = None
29+
for line in response.text.strip().splitlines():
30+
entry = json.loads(line)
31+
cid_v0 = entry.get("Hash")
2732

28-
async def upload_site(files: list[Path], multiaddr: Multiaddr) -> CID:
29-
client = aioipfs.AsyncIPFS(
30-
maddr=multiaddr,
31-
read_timeout=900,
32-
)
33+
if not cid_v0:
34+
raise RuntimeError("CID not found in response.")
3335

34-
try:
35-
cid = None
36-
async for added_file in client.add(*files, recursive=True):
37-
logger.debug(
38-
f"Uploaded file {added_file['Name']} with CID: {added_file['Hash']}"
39-
)
40-
cid = added_file["Hash"]
41-
# The last CID is the CID of the directory uploaded
42-
return cid or raise_no_cid()
43-
finally:
44-
await client.close()
36+
cid_v1 = make_cid(cid_v0).to_v1().encode("base32").decode()
37+
return {"cid_v0": cid_v0, "cid_v1": cid_v1}
4538

46-
47-
async def publish_site(path: Path, multiaddr: Multiaddr) -> CID:
39+
if __name__ == "__main__":
40+
path = Path(sys.argv[1])
4841
if not path.is_dir():
49-
raise NotADirectoryError(f"No such directory: {path}")
50-
cid = await upload_site(files=[path], multiaddr=multiaddr)
51-
return cid
52-
53-
54-
def main():
55-
if len(sys.argv) != 2:
56-
print(f"Usage: {Path(__file__).name} <directory>")
42+
print("Error: path must be a directory")
5743
sys.exit(1)
5844

59-
directory = Path(sys.argv[1]).resolve()
60-
print(asyncio.run(publish_site(directory, Multiaddr("/dns4/ipfs-2.aleph.im/tcp/443/https"))))
61-
62-
63-
if __name__ == "__main__":
64-
logging.basicConfig(level=logging.INFO)
65-
main()
45+
result = upload_with_requests(path.resolve(), "https://ipfs-2.aleph.im")
46+
print(json.dumps(result))

push-to-ipfs/scripts/requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
requests==2.32.4
2+
py-cid==0.3.0

0 commit comments

Comments
 (0)