Skip to content

Commit 661e3f8

Browse files
committed
fix: Refactorize exporter
1 parent 9c565bd commit 661e3f8

4 files changed

Lines changed: 72 additions & 57 deletions

File tree

Lines changed: 33 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,26 @@
44
import os
55
import sys
66
import argparse
7+
from notion2md.console import print_error
78

8-
def cli():
9+
class Config(object):
10+
__slots__ = ("file_name", "target_id", "output_path","exporter_type")
11+
def __init__(self,args:dict):
12+
self.file_name = args["name"] if args["name"] else args["id"]
13+
14+
self.output_path = os.path.abspath(args["path"]) if args["path"] \
15+
else os.path.join(os.getcwd(),'notion2md-output')
16+
17+
self.target_id = get_id(args["url"]) if args["url"] else args["id"]
18+
19+
if not self.target_id:
20+
print_error("please enter Notion page's id or url")
21+
print()
22+
sys.exit(1)
23+
24+
self.exporter_type = args["type"]
25+
26+
def parse_config() -> dict:
927
parser = argparse.ArgumentParser(description="Notion2md: Notion to Markdown Exporter")
1028
parser.add_argument('--type','-t',type=str,help="Set a type of target page: block, page, database",default="block")
1129
parser.add_argument('--url','-u',type=str,help="Set an url of target page")
@@ -14,32 +32,26 @@ def cli():
1432
parser.add_argument('--name','-n',type=str,help="Set a custom name of output file")
1533
parser.add_argument('--version','-v', action='store_true',help="Show a version of Notion2Md")
1634

17-
args = parser.parse_args()
18-
19-
if args.version:
20-
print(notion2md.__version__)
21-
sys.exit()
22-
23-
def get_url():
24-
return input("Enter Notion Url: ")
25-
26-
custom_name = args.name if args.name else ""
27-
28-
target_id = get_id(args.url) if args.url \
29-
else ( args.id if args.id \
30-
else get_id(get_url()))
31-
32-
output_path = os.path.abspath(args.path) if args.path \
33-
else os.path.join(os.getcwd(),'notion2md-output')
35+
return vars(parser.parse_args())
3436

37+
def call_exporter(config:Config):
3538
target_type_map ={
3639
'block': block_exporter,
3740
# 'page': page_exporter,
3841
# 'database': database
3942
}
4043

41-
target_type_map[args.type](target_id,output_path,custom_name)
44+
target_type_map[config.exporter_type](config)
45+
46+
def cli():
47+
48+
args = parse_config()
4249

43-
# page_exporter()
50+
if args["version"]:
51+
print(notion2md.__version__)
52+
sys.exit(None)
4453

45-
# database_exporter()
54+
config = Config(args)
55+
print()
56+
call_exporter(config)
57+
print()

notion2md/console.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import os
2+
3+
os.system("")
4+
5+
class Style():
6+
BLACK = '\033[30m'
7+
RED = '\033[31m'
8+
GREEN = '\033[32m'
9+
YELLOW = '\033[33m'
10+
BLUE = '\033[34m'
11+
MAGENTA = '\033[35m'
12+
CYAN = '\033[36m'
13+
WHITE = '\033[37m'
14+
UNDERLINE = '\033[4m'
15+
BOLD = '\033[1m'
16+
RESET = '\033[0m'
17+
18+
def print_error(message):
19+
print(f"{Style.RED}{Style.BOLD}{'ERROR'+' ':>12}{Style.RESET}{message}")
20+
21+
def print_status(status,message):
22+
print(f"{Style.GREEN}{Style.BOLD}{status+' ':>12}{Style.RESET}{message}")

notion2md/exporter.py

Lines changed: 13 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,26 @@
1-
from notion2md.client_handler import notion_client_object
1+
from notion2md.notion_client import notion_client_object
22
from notion2md.convertor.block import blocks_convertor
3+
from notion2md.cli import Config
34
import os
45
import time
6+
from notion2md.console import print_status
57

6-
os.system("")
7-
8-
class style():
9-
BLACK = '\033[30m'
10-
RED = '\033[31m'
11-
GREEN = '\033[32m'
12-
YELLOW = '\033[33m'
13-
BLUE = '\033[34m'
14-
MAGENTA = '\033[35m'
15-
CYAN = '\033[36m'
16-
WHITE = '\033[37m'
17-
UNDERLINE = '\033[4m'
18-
BOLD = '\033[1m'
19-
UNDERLINE = '\033[4m'
20-
RESET = '\033[0m'
21-
22-
def fprint(left,right):
23-
print(f"{style.GREEN}{style.BOLD}{left+' ':>12}{style.RESET}{right}")
24-
25-
def block_exporter(target_id:str,output_path="notion2md-output",custom_name=""):
8+
def block_exporter(config:Config):
269
start_time = time.time()
2710
#Directory Checking and Creating
28-
if not os.path.exists(output_path):
29-
os.mkdir(output_path)
30-
#Get title from parent page block
31-
block_title = custom_name if custom_name \
32-
else target_id
11+
if not os.path.exists(config.output_path):
12+
os.mkdir(config.output_path)
3313
#Get actual blocks
34-
print()
35-
fprint("Retrieving",f"blocks from '{target_id}'")
36-
blocks = notion_client_object.blocks.children.list(target_id)['results']
14+
15+
print_status("Retrieving",f"blocks from '{config.target_id}'")
16+
blocks = notion_client_object.blocks.children.list(config.target_id)['results']
3717
#Write(Export) Markdown file
38-
with open(os.path.join(output_path,block_title+'.md'),'w',encoding="utf-8") as output:
18+
with open(os.path.join(config.output_path,config.file_name + '.md'),'w',encoding="utf-8") as output:
3919
output.write(blocks_convertor(blocks))
20+
4021
#Result and Time Check
41-
fprint("Converted", f"{str(len(blocks))} blocks to markdown in {time.time() - start_time:.2f}s")
42-
fprint("Exported", f'"{block_title}.md" in "{os.path.abspath(output_path)}/"')
43-
print()
22+
print_status("Converted", f"{str(len(blocks))} blocks to markdown in {time.time() - start_time:.2f}s")
23+
print_status("Exported", f'"{config.file_name}.md" in "{os.path.abspath(config.output_path)}/"')
4424

4525
# page_exporter()
4626

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
from notion_client import Client #,AsyncClient
22
import os,sys
3+
from notion2md.console import print_error
34

45
try:
56
notion_client_object = Client(auth=os.environ["NOTION_TOKEN"])
67
except:
8+
print_error("Notion Integration Token is not found")
9+
print()
710
print(
811
"""
9-
Token Error
10-
1112
Welcome to notion2md!
1213
1314
To get started, you need to save your Notion Integration Token.
@@ -23,5 +24,5 @@
2324
put upper command in your shell resource(ex: .bashrc or .zshrc)
2425
"""
2526
)
26-
sys.exit()
27+
sys.exit(1)
2728
# notion_async_client = AsyncClient(auth=os.environ["NOTION_TOKEN"])

0 commit comments

Comments
 (0)