Skip to content

Commit 2f3dc47

Browse files
committed
Test Commit: test qiita
1 parent 6094679 commit 2f3dc47

File tree

3 files changed

+68
-28
lines changed

3 files changed

+68
-28
lines changed

.github/scripts/sync_qiita.py

+44-21
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,30 @@
11
import os
22
import json
33
import requests
4+
import subprocess
45
from pathlib import Path
56

67
# Qiita APIの設定
78
QIITA_API_URL = "https://qiita.com/api/v2/items"
8-
QIITA_ACCESS_TOKEN = os.getenv("QIITA_API_TOKEN")
9+
QIITA_ACCESS_TOKEN = os.getenv("QIITA_ACCESS_TOKEN")
910

1011
# 記事/IDを管理するファイルのパス
1112
POSTS_DIR = "qiita_posts/"
12-
ARTICLE_IDS_FILE = Path(".github/scripts/qiita_article_ids.json")
13+
ARTICLE_IDS_FILE = Path("qiita_article_ids.json")
1314

1415
# qiita_posts ディレクトリ内の変更されたファイルを取得する関数
1516
def get_modified_files():
16-
# git diff を使って、qiita_posts/ 内で変更されたファイルを取得
17-
result = subprocess.run(
18-
["git", "diff", "--name-only", "HEAD", POSTS_DIR],
19-
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
20-
)
21-
modified_files = result.stdout.splitlines()
17+
try:
18+
# git diff を使って、qiita_posts/ 内で変更されたファイルを取得
19+
result = subprocess.run(
20+
["git", "diff", "--name-only", "HEAD~", "HEAD", POSTS_DIR],
21+
check=True,
22+
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
23+
)
24+
modified_files = result.stdout.splitlines()
25+
except subprocess.CalledProcessError as e:
26+
print(f'Error: {e.stderr}')
27+
2228
return modified_files
2329

2430
# Qiitaに記事を投稿または更新する関数
@@ -33,20 +39,29 @@ def post_or_update_article(file_path, article_id=None):
3339
print(f"Updating article: {article_id}")
3440
response = requests.patch(
3541
f"{QIITA_API_URL}/{article_id}",
36-
headers={"Authorization": f"Bearer {ACCESS_TOKEN}"},
42+
headers={"Authorization": f"Bearer {QIITA_ACCESS_TOKEN}"},
3743
json={"body": content}
3844
)
3945
else:
4046
# 新規投稿
4147
print(f"Creating new article from {file_path.name}")
48+
49+
title = file_path.stem
50+
if len(title) < 1:
51+
raise ValueError("タイトルは1文字以上でなければなりません。")
52+
body = content
53+
if len(body) < 20: # 20文字以上の本文を求める
54+
raise ValueError("本文は20文字以上でなければなりません。")
55+
4256
response = requests.post(
4357
QIITA_API_URL,
44-
headers={"Authorization": f"Bearer {ACCESS_TOKEN}"},
45-
json={"title": file_path.stem, "body": content, "tags": [], "private": True} # プライベート設定
58+
headers={"Authorization": f"Bearer {QIITA_ACCESS_TOKEN}"},
59+
json={"title": file_path.stem, "body": body, "tags": [{"name":"Ruby", "versions": ["0.0.1"]}], "private": True} # プライベート設定
4660
)
61+
print({"title": title, "body": content, "tags": [], "private": True})
4762

4863
# エラーチェック
49-
if response.status_code == 200:
64+
if response.status_code in [200, 201]:
5065
return response.json()["id"]
5166
else:
5267
print(f"Error: {response.status_code} - {response.text}")
@@ -62,7 +77,7 @@ def update_article_ids(new_article_id):
6277
data = {"article_ids": []}
6378

6479
# 新しい記事IDを追加
65-
if new_article_id not in data["article_ids"]:
80+
if new_article_id not in data.get("article_ids"):
6681
data["article_ids"].append(new_article_id)
6782

6883
# JSONファイルを更新
@@ -79,22 +94,30 @@ def sync_articles():
7994
file_path = Path(file)
8095

8196
# 変更されたファイルが qiita_posts/ に含まれているか確認
82-
if file_path.startswith(POSTS_DIR) and file_path.suffix == ".md": # TODO Path.globでやるのもあり。
97+
if file.startswith(POSTS_DIR) and file_path.suffix == ".md": # TODO Path.globでやるのもあり。
8398
article_id = None
8499
# article_id がすでに JSON に存在するか確認
85-
with open(ARTICLE_IDS_FILE, "r", encoding="utf-8") as f:
86-
data = json.load(f)
87-
for existing_article_id in data["article_ids"]:
88-
if existing_article_id in file.name:
89-
article_id = existing_article_id
90-
break
100+
try:
101+
if ARTICLE_IDS_FILE.exists():
102+
with open(ARTICLE_IDS_FILE, "r", encoding="utf-8") as f:
103+
data = json.load(f)
104+
else:
105+
data = {"article_ids": []}
106+
107+
for existing_article_id in data.get("article_ids"):
108+
if existing_article_id in file.name:
109+
article_id = existing_article_id
110+
break
111+
except (FileNotFoundError, PermissionError) as e:
112+
pass # 例外を無視して処理を続ける
91113

92114
# Qiita に記事を投稿または更新
93-
new_article_id = post_or_update_article(file, article_id)
115+
new_article_id = post_or_update_article(file_path, article_id)
94116

95117
# 成功した場合は記事IDを更新
96118
if new_article_id:
97119
update_article_ids(new_article_id)
98120

121+
99122
if __name__ == "__main__":
100123
sync_articles()

.github/workflows/qiita-post.yml

+15-4
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,14 @@ jobs:
1212

1313
steps:
1414
- name: Checkout repository
15-
uses: actions/checkout@v3
15+
uses: actions/checkout@v4
16+
with:
17+
fetch-depth: 2 # リポジトリの最新2件の履歴を取得
1618

1719
- name: Set up Python
18-
uses: actions/setup-python@v4
20+
uses: actions/setup-python@v5
1921
with:
20-
python-version: 3.10
22+
python-version: '3.12.7'
2123

2224
- name: Install dependencies
2325
run: |
@@ -29,10 +31,19 @@ jobs:
2931
QIITA_ACCESS_TOKEN: ${{ secrets.QIITA_API_TOKEN }}
3032
run: python .github/scripts/sync_qiita.py
3133

34+
- name: Check for changes in qiita_posts
35+
id: check_changes
36+
run: |
37+
# qiita_article_ids.json を変更対象として確認
38+
git diff --quiet qiita_article_ids.json
39+
echo "Changes detected in qiita_article_ids.json: $?"
40+
continue-on-error: true # git diff がエラーを返してもエラーとして扱わない
41+
3242
- name: Commit updated article IDs
43+
if: steps.check_changes.outcome == 'failure' # 変更があった場合にのみ実行
3344
run: |
3445
git config --global user.name "github-actions[bot]"
3546
git config --global user.email "github-actions[bot]@users.noreply.github.com"
36-
git add .github/scripts/qiita_article_ids.json
47+
git add qiita_article_ids.json
3748
git commit -m "Update article IDs"
3849
git push

qiita_posts/test.md

+9-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
1-
# aa
1+
# aadさdさ
22

3-
# foo
3+
## foo
44

55
```bash
66
print hello
7-
```
7+
```
8+
dさんdそあ
9+
あskjbんじあsんb
10+
11+
Delta compression using up to 16 threads
12+
Compressing objects: 100% (5/5), done.
13+
Writing objects: 100% (9/9), 1.43 KiB

0 commit comments

Comments
 (0)