11import os
22import json
33import requests
4+ import subprocess
45from pathlib import Path
56
67# Qiita APIの設定
910
1011# 記事/IDを管理するファイルのパス
1112POSTS_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 ディレクトリ内の変更されたファイルを取得する関数
1516def 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に記事を投稿または更新する関数
@@ -45,6 +51,7 @@ def post_or_update_article(file_path, article_id=None):
4551 json = {"title" : file_path .stem , "body" : content , "tags" : [], "private" : True } # プライベート設定
4652 )
4753
54+ # print(f"Debug: {response}")
4855 # エラーチェック
4956 if response .status_code == 200 :
5057 return response .json ()["id" ]
@@ -62,7 +69,7 @@ def update_article_ids(new_article_id):
6269 data = {"article_ids" : []}
6370
6471 # 新しい記事IDを追加
65- if new_article_id not in data [ "article_ids" ] :
72+ if new_article_id not in data . get ( "article_ids" ) :
6673 data ["article_ids" ].append (new_article_id )
6774
6875 # JSONファイルを更新
@@ -82,12 +89,15 @@ def sync_articles():
8289 if file_path .startswith (POSTS_DIR ) and file_path .suffix == ".md" : # TODO Path.globでやるのもあり。
8390 article_id = None
8491 # 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 # 例外を無視して処理を続ける
91101
92102 # Qiita に記事を投稿または更新
93103 new_article_id = post_or_update_article (file , article_id )
@@ -96,5 +106,6 @@ def sync_articles():
96106 if new_article_id :
97107 update_article_ids (new_article_id )
98108
109+
99110if __name__ == "__main__" :
100111 sync_articles ()
0 commit comments