1
1
import os
2
2
import json
3
3
import requests
4
+ import subprocess
4
5
from pathlib import Path
5
6
6
7
# Qiita APIの設定
7
8
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 " )
9
10
10
11
# 記事/IDを管理するファイルのパス
11
12
POSTS_DIR = "qiita_posts/"
12
- ARTICLE_IDS_FILE = Path (".github/scripts/ qiita_article_ids.json" )
13
+ ARTICLE_IDS_FILE = Path ("qiita_article_ids.json" )
13
14
14
15
# qiita_posts ディレクトリ内の変更されたファイルを取得する関数
15
16
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
+
22
28
return modified_files
23
29
24
30
# Qiitaに記事を投稿または更新する関数
@@ -33,20 +39,29 @@ def post_or_update_article(file_path, article_id=None):
33
39
print (f"Updating article: { article_id } " )
34
40
response = requests .patch (
35
41
f"{ QIITA_API_URL } /{ article_id } " ,
36
- headers = {"Authorization" : f"Bearer { ACCESS_TOKEN } " },
42
+ headers = {"Authorization" : f"Bearer { QIITA_ACCESS_TOKEN } " },
37
43
json = {"body" : content }
38
44
)
39
45
else :
40
46
# 新規投稿
41
47
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
+
42
56
response = requests .post (
43
57
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 } # プライベート設定
46
60
)
61
+ print ({"title" : title , "body" : content , "tags" : [], "private" : True })
47
62
48
63
# エラーチェック
49
- if response .status_code == 200 :
64
+ if response .status_code in [ 200 , 201 ] :
50
65
return response .json ()["id" ]
51
66
else :
52
67
print (f"Error: { response .status_code } - { response .text } " )
@@ -62,7 +77,7 @@ def update_article_ids(new_article_id):
62
77
data = {"article_ids" : []}
63
78
64
79
# 新しい記事IDを追加
65
- if new_article_id not in data [ "article_ids" ] :
80
+ if new_article_id not in data . get ( "article_ids" ) :
66
81
data ["article_ids" ].append (new_article_id )
67
82
68
83
# JSONファイルを更新
@@ -79,22 +94,30 @@ def sync_articles():
79
94
file_path = Path (file )
80
95
81
96
# 変更されたファイルが 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でやるのもあり。
83
98
article_id = None
84
99
# 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 # 例外を無視して処理を続ける
91
113
92
114
# Qiita に記事を投稿または更新
93
- new_article_id = post_or_update_article (file , article_id )
115
+ new_article_id = post_or_update_article (file_path , article_id )
94
116
95
117
# 成功した場合は記事IDを更新
96
118
if new_article_id :
97
119
update_article_ids (new_article_id )
98
120
121
+
99
122
if __name__ == "__main__" :
100
123
sync_articles ()
0 commit comments