Skip to content

Commit

Permalink
Add ANSI colors support
Browse files Browse the repository at this point in the history
  • Loading branch information
hemanta212 committed Oct 29, 2019
1 parent bf026a8 commit 8589ea4
Show file tree
Hide file tree
Showing 14 changed files with 115 additions and 53 deletions.
13 changes: 8 additions & 5 deletions blogger_cli/blog_manager/add_post.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,10 @@ def get_navbar_dict(ctx, snippet_content_map, topic):
snippet_content_map["navbar_data"], object_pairs_hook=OrderedDict
)
except Exception as E:
ctx.log("Couldnot parse your custom navbar", E)
raise SystemExit("ERROR: INVALID NAVBAR TEMPLATE")
ctx.log(
":: Could not parse your custom navbar", E, "ERROR: INVALID NAVBAR TEMPLATE"
)
raise SystemExit()

if topic:
for nav_topic, nav_link in navbar_dict.items():
Expand Down Expand Up @@ -187,15 +189,15 @@ def update_posts_index(ctx, snippet_content_map, meta):
topic = meta["topic"]

if not os.path.exists(index_path):
ctx.vlog("Cannot find index file in", index_path)
ctx.vlog(":: Cannot find index file in", index_path)
ctx.log("WARNING: NO INDEX FILE. SEE blogger export --help")
return None

soup = BS(read_file(index_path), features="html.parser")
posts_list_div = soup.find("div", class_=index_div_class)

if not posts_list_div:
ctx.log("Cannot update blog index. No div with", index_div_class, "class")
ctx.log(":: Cannot update blog index! No div with", index_div_class, "class")
ctx.log("WARNING: INVALID INDEX.", index_path)
return None

Expand Down Expand Up @@ -293,7 +295,8 @@ def filter_invalid_index_links(ctx, soup, blog_posts_dir):
or href_data.startswith("data:")
):
raise ValueError
except:
except Exception as E:
ctx.vlog(E)
href_data = None

if href_data:
Expand Down
14 changes: 10 additions & 4 deletions blogger_cli/blog_manager/add_post_meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def get_blog_posts_dir(ctx):
blog = ctx.current_blog
blog_posts_dir = ctx.config.read(blog + ":blog_posts_dir")
if not blog_posts_dir:
ctx.log(":: Failed to build file link, no proper blog dir")
ctx.log(":: Failed to build file link! no proper blog dir")
blog_posts_dir = ""
return blog_posts_dir

Expand Down Expand Up @@ -55,16 +55,22 @@ def get_post_meta(ctx, file_path, post_meta):
del post_meta[key]

if not post_meta:
click.echo(
click.secho(
(
":: ERROR: Metadata extraction from cache failed for "
+ topic_filename
+ "\n:: TIP: Use --title and --content option instead"
)
),
blink=True,
bold=True,
fg="bright_red",
)

if post_meta and not post_meta.get("content"):
click.echo(":: Warning, No available content for " + blog_topic_filename)
click.secho(
":: Warning, No available content for " + blog_topic_filename,
fg="bright_yellow",
)
return post_meta


Expand Down
17 changes: 16 additions & 1 deletion blogger_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,25 @@ def __init__(self):

def log(self, msg, *args):
"""Logs a message to stderr."""
msg = str(msg)
if args:
for arg in args:
msg += " " + str(arg)
click.echo(msg, file=sys.stderr)

message = msg.lower() if msg else ""

# handle basic coloring
if "error" in message:
click.secho(msg, file=sys.stderr, bold=True, blink=True, fg="bright_red")
elif "warning" in message or "!" in message:
click.secho(msg, file=sys.stderr, bold=True, fg="bright_yellow")
elif "converting" in message or "adding" in message:
click.secho(msg, file=sys.stderr, fg="blue")
elif "finished" in message or "done" in message or "successfully" in message:
click.secho(msg, file=sys.stderr, fg="green")

else:
click.echo(msg, file=sys.stderr)

def vlog(self, msg, *args):
"""Logs a message to stderr only if verbose is enabled."""
Expand Down
36 changes: 21 additions & 15 deletions blogger_cli/commands/cmd_addfeed.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,15 @@ def cli(ctx, file_path, gen_rss, interactive, title, content, setup, blog, verbo
run_setup(ctx, blog, feed_file, feed_type)

elif not file_path:
raise SystemExit(":: ERROR. <FILE> argument is not provided")
ctx.log(":: ERROR. <FILE> argument is not provided")
raise SystemExit()

elif not __is_valid_feed_file(ctx, blog):
msg = (
ctx.log(
":: ERROR parsing feed file! Review it or create new one using\n"
"$ blogger addfeed -b <blogname> --setup"
)
raise SystemExit(msg)
raise SystemExit()

ctx.log(":: PROCESSING ", file_path)
feed_file = __get_feed_file(ctx, blog)
Expand Down Expand Up @@ -76,14 +77,15 @@ def run_setup(ctx, blog, feed_file, feed_type):
feed_file = __get_feed_file(ctx, blog)
# Create a new feed file
setup_new_file(feed_file, feed_type)
raise SystemExit("Setup successfully completed!")
ctx.log("Setup successfully completed!")


def __get_blog(ctx, blog):
if blog is None:
default = ctx.default_blog
if default is None:
raise SystemExit("\nError: Missing option -b <blogname>")
ctx.log("\nError: Missing option -b <blogname>")
raise SystemExit()

else:
ctx.vlog("\nUsing default blog ->", default)
Expand All @@ -101,7 +103,8 @@ def __get_feed_file(ctx, blog):
"or provide its path in config by:\n"
"blogger config -b {blog} feed_file <path/of/feed/file>"
)
raise SystemExit(msg.format(blog=blog))
raise ctx.log(msg.format(blog=blog))
raise SystemExit()

feed_file_path = os.path.join(blog_dir, feed_file)
return feed_file_path
Expand All @@ -120,7 +123,8 @@ def __is_valid_feed_file(ctx, blog):
if feed_file:
# Create a new feed file and return false
if not blog_dir:
raise SystemExit(":: ERROR 'blog_dir' config is empty")
ctx.log(":: ERROR 'blog_dir' config is empty")
raise SystemExit()
feed_file_path = os.path.join(blog_dir, feed_file)
if not os.path.exists(feed_file_path):
ensure_feed_file(feed_file_path)
Expand All @@ -147,7 +151,8 @@ def load_editor():
if not message:
raise ValueError
except Exception:
raise SystemExit(":: Empty file. Aborting...")
click.secho(":: ERROR empty file. Aborting...", bold=True, fg="bright_red")
raise SystemExit()

title_content = message.split("\n\n", maxsplit=1)
title = title_content[0]
Expand All @@ -165,11 +170,12 @@ def ensure_feed_file(feed_file_path):
return

except FileNotFoundError:
raise SystemExit(
":: ERROR Is the blog just created? \n"
+ ":: Path: "
+ feed_file_path
+ " doesnot exist"
+ " \n:: TIP: Convert some files or export blog_layout"
+ " or create folder manually"
msg = (
":: ERROR Is the blog just created? \n",
":: Path: ",
+feed_file_path + " doesnot exist",
" \n:: TIP: Convert some files or export blog_layout",
" or create folder manually",
)
click.secho(msg, bold=True, blink=True, fg="bright_red")
raise SystemExit()
9 changes: 5 additions & 4 deletions blogger_cli/commands/cmd_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,8 @@ def cli(ctx, remove, blog, configs, restore, verbose):
raise SystemExit(0)

if not configs:
raise SystemExit(
"ERROR: MISSING ARGUMENT 'CONFIG KEY'" + " See blogger config --help"
)
ctx.log("ERROR: MISSING ARGUMENT 'CONFIG KEY'", " \nSee blogger config --help")
raise SystemExit()

__validate(ctx, blog, configs)
key = configs[0]
Expand All @@ -65,7 +64,9 @@ def ensure_and_expand_dir(dir):
try:
full_path = str(folder.expanduser().resolve())
except FileNotFoundError as E:
raise SystemExit("ERROR:", E, dir)
msg = "ERROR:" + str(E) + str(dir)
click.secho(msg, blink=True, bold=True, fg="bright_red")
raise SystemExit()

return full_path

Expand Down
18 changes: 12 additions & 6 deletions blogger_cli/commands/cmd_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,8 @@ def cli(
"topic": topic,
}
filenames_meta = convert_and_copyfiles(ctx)
ctx.log("Converted files successfully.\n\nADDING FILES TO BLOG")
ctx.log("Converted files successfully. \n")
ctx.log("ADDING FILES TO BLOG")
for filename_meta in filenames_meta:
add_post.add(ctx, filename_meta)

Expand All @@ -153,7 +154,8 @@ def get_files_from_working_dir(ctx, recursive):
working_dir = Path(str(working_dir))
if not working_dir or not working_dir.exists():
ctx.log(":: Working folder doesnot exist")
raise SystemExit(":: ERROR: No input files")
ctx.log(":: ERROR: No input files")
raise SystemExit()

current_timestamp = datetime.today().timestamp()
ctx.config.write(blog + ":working_dir_timestamp", current_timestamp)
Expand All @@ -167,8 +169,9 @@ def get_files_from_working_dir(ctx, recursive):
ctx.log(
"Parse error for last sync. Please convert",
"files manually or convert all files in your working_dir",
"ERROR: Last sync date invalid",
)
raise SystemExit("ERROR: Last sync date invalid")
raise SystemExit()

def is_modified_file(path):
if not path.is_file():
Expand Down Expand Up @@ -235,8 +238,9 @@ def check_and_ensure_destination_dir(ctx, output_dir):
"setup in your",
blog,
"blog's config",
"ERROR: NO OUTPUT FOLDER",
)
raise SystemExit("ERROR: NO OUTPUT FOLDER")
raise SystemExit()

if posts_dir:
destination_dir = os.path.join(blog_dir, posts_dir)
Expand Down Expand Up @@ -269,7 +273,8 @@ def check_and_ensure_img_dir(ctx, destination_dir, output_img_dir):
img_dir = os.path.join(destination_dir, "images")
return img_dir
else:
raise SystemExit("ERROR: NO OUTPUT FOLDER")
ctx.log("ERROR: NO OUTPUT FOLDER")
raise SystemExit()

if blog_img_dir:
img_dir = os.path.join(blog_dir, blog_img_dir)
Expand Down Expand Up @@ -304,7 +309,8 @@ def set_current_blog(ctx, blog):

if not ctx.blog_exists(current_blog):
ctx.log("Blog name not given. Use --blog option or set default blog")
raise SystemExit("ERROR: Blogname unavailable. SEE blogger convert --help")
ctx.log("ERROR: Blogname unavailable. SEE blogger convert --help")
raise SystemExit()

ctx.current_blog = current_blog

Expand Down
12 changes: 8 additions & 4 deletions blogger_cli/commands/cmd_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ def cli(ctx, resource, blog, relative_path, verbose):
transfer = resource_map.get(resource)
if not transfer:
ctx.log("No such resource. See blogger export --help")
raise SystemExit("ERROR: INVALID RESOURCE NAME")
ctx.log("ERROR: INVALID RESOURCE NAME")
raise SystemExit()

ctx.vlog("Using function", transfer)
transfer(ctx, export_path)
Expand All @@ -64,11 +65,13 @@ def validate_blog_and_settings(ctx, input_blog, input_path):
settings = ctx.config.read(key=blog + ": blog_dir")
if not settings and not input_path:
ctx.log("Set config value for blog_dir in", blog, "blog")
raise SystemExit("ERROR: MISSING CONFIG: blog_dir")
ctx.log("ERROR: MISSING CONFIG: blog_dir")
raise SystemExit()

elif not blog or not blog_exists:
ctx.log("Pass a correct blog with -b option", "or set a default blog")
raise SystemExit("ERROR: INVALID_BLOG_NAME: " + str(blog))
ctx.log("ERROR: INVALID_BLOG_NAME: " + str(blog))
raise SystemExit()

ctx.current_blog = blog

Expand All @@ -83,7 +86,8 @@ def resolve_export_path(ctx, relative_path):
relative_path,
"without setting blog_dir value in config!",
)
raise SystemExit("Use full path to export in this folder")
ctx.log(":: ERROR use full path to export in this folder")
raise SystemExit()
else:
blog_dir = ""

Expand Down
8 changes: 5 additions & 3 deletions blogger_cli/commands/cmd_serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,17 @@ def cli(ctx, blog, port, dir, verbose):
ctx.vlog(":: No blog name given using default blog:", str(blog))
if not blog:
ctx.log("Use blogger serve <blogname> or set a default blog in configs")
raise SystemExit("ERROR: Missing required argument 'BLOG' ")
ctx.log("ERROR: Missing required argument 'BLOG' ")
raise SystemExit()

blog_dir = ctx.config.read(key=blog + ":blog_dir")
if dir:
blog_dir = dir

if not blog_dir:
ctx.log("CNo blog_dir set blog_dir in config or use --dir option")
raise SystemExit("ERROR: No folder specified")
ctx.log("No blog_dir set blog_dir in config or use --dir option")
ctx.log("ERROR: No folder specified")
raise SystemExit()

blog_dir = os.path.abspath(os.path.expanduser(blog_dir))
ctx.vlog(":: Got blog_dir:", blog_dir)
Expand Down
12 changes: 9 additions & 3 deletions blogger_cli/commands/cmd_uninstall.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,13 @@ def cli():

custom = [False for i in [".blogger_cli", "venv"] if i not in ROOT_DIR]
if False in custom:
print("blogger-cli was not installed by recommended method")
raise SystemExit("Use pip uninstall blogger-cli instead to uninstall")
click.secho(
"blogger-cli was not installed by recommended method",
":: ERROR use pip uninstall blogger-cli instead to uninstall",
bold=True,
fg="bright_red",
)
raise SystemExit()

if not WINDOWS:
installer = Installer()
Expand All @@ -30,9 +35,10 @@ def cli():
installer_path = resource_filename("blogger_cli", installer_location)
shutil.copyfile(installer_path, new_file_path)

print(
msg = (
"Please run this command manually to Uninstall:\n",
"python",
new_file_path,
"--uninstall",
)
click.secho(msg, fg="green")
12 changes: 9 additions & 3 deletions blogger_cli/commands/cmd_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,13 @@ def cli(version, force, accept_all):

custom = [False for i in [".blogger_cli", "venv"] if i not in ROOT_DIR]
if False in custom:
print("blogger-cli was not installed by recommended method")
raise SystemExit("Use pip install --upgrade blogger-cli instead to upgrade")
click.secho(
"blogger-cli was not installed by recommended method",
"Use pip install --upgrade blogger-cli instead to upgrade",
bold=True,
fg="bright_red",
)
raise SystemExit()

if not WINDOWS or not force:
installer = Installer(version=version, force=force, accept_all=accept_all)
Expand All @@ -37,9 +42,10 @@ def cli(version, force, accept_all):
if accept_all:
last_string += " -y "

print(
msg = (
"Please run this command manually to force update!:\n",
"python",
new_file_path,
last_string,
)
click.secho(msg, fg="green")
Loading

0 comments on commit 8589ea4

Please sign in to comment.