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の設定
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に記事を投稿または更新する関数
@@ -45,6 +51,7 @@ def post_or_update_article(file_path, article_id=None):
45
51
json = {"title" : file_path .stem , "body" : content , "tags" : [], "private" : True } # プライベート設定
46
52
)
47
53
54
+ # print(f"Debug: {response}")
48
55
# エラーチェック
49
56
if response .status_code == 200 :
50
57
return response .json ()["id" ]
@@ -62,7 +69,7 @@ def update_article_ids(new_article_id):
62
69
data = {"article_ids" : []}
63
70
64
71
# 新しい記事IDを追加
65
- if new_article_id not in data [ "article_ids" ] :
72
+ if new_article_id not in data . get ( "article_ids" ) :
66
73
data ["article_ids" ].append (new_article_id )
67
74
68
75
# JSONファイルを更新
@@ -82,12 +89,15 @@ def sync_articles():
82
89
if file_path .startswith (POSTS_DIR ) and file_path .suffix == ".md" : # TODO Path.globでやるのもあり。
83
90
article_id = None
84
91
# 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
92
+ try :
93
+ with open (ARTICLE_IDS_FILE , "r" , encoding = "utf-8" ) as f :
94
+ data = json .load (f )
95
+ for existing_article_id in data .get ("article_ids" ):
96
+ if existing_article_id in file .name :
97
+ article_id = existing_article_id
98
+ break
99
+ except (FileNotFoundError , PermissionError ) as e :
100
+ pass # 例外を無視して処理を続ける
91
101
92
102
# Qiita に記事を投稿または更新
93
103
new_article_id = post_or_update_article (file , article_id )
@@ -96,5 +106,6 @@ def sync_articles():
96
106
if new_article_id :
97
107
update_article_ids (new_article_id )
98
108
109
+
99
110
if __name__ == "__main__" :
100
111
sync_articles ()
0 commit comments