Skip to content

Commit

Permalink
convert config to ini file.
Browse files Browse the repository at this point in the history
  • Loading branch information
rahulunair committed Feb 14, 2021
1 parent 8f9a285 commit fa9b22a
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 46 deletions.
13 changes: 12 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ sh = "^1.14.1"
aiofiles = "^0.6.0"
loguru = "^0.5.3"
shellingham = "^1.4.0"
ciso8601 = "^2.1.3"

[tool.poetry.dev-dependencies]
pytest = "^5.2"
Expand Down
24 changes: 24 additions & 0 deletions src/github_peek/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,25 @@
__version__ = "0.1.0"

import os
from pathlib import Path

config_file = Path.home() / ".githubkeep.ini"
config_text = '''
[DEFAULT]
editor = "vim"
cache_repos = 1
# how many minutes should each repo be kept in cache
cache_delta = 3
cache_loc = ""
github_token = ""
gitlab_token = ""
[proxy_settings]
https_proxy = ""
http_proxy = ""
'''
if not os.path.exists(config_file):
with open(config_file, "w") as fh:
fh.write(config_text)


4 changes: 2 additions & 2 deletions src/github_peek/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ def peek(repo: str):
typer.secho(f"opening repo: {repo}...", fg=typer.colors.GREEN)
main(repo)
except Exception:
typer.echo(f"failed to peek {repo}")
raise typer.Abort()
typer.echo(f"failed to peek {repo}")
raise typer.Abort()


@app.command()
Expand Down
59 changes: 41 additions & 18 deletions src/github_peek/config.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,47 @@
import os
import configparser
from datetime import datetime
from datetime import timedelta
from pathlib import Path

GITHUB_API = "https://api.github.com/repos/{owner}/{repo}/tarball/master"
EDITORS = ["vim", "vi", "nvim", "nano", "code", "emacs"]


def config(cfg_file=".githubkeep.conf"):
"""set global config setting"""
# TODO(unrahul): change to ini logger
config_file = Path.home() / cfg_file
template = "{}={}"
exists = os.path.isfile(config_file)
if exists:
with open(config_file, "r") as rh:
line = rh.readline()
count = int(line.split("=")[1])
count -= 1
else:
count = 5
with open(config_file, "w") as fh:
fh.writelines(template.format("count_till_cache_delete", count))
fh.flush()
return config_file
class Config:
def __init__(self, cfg_file=".githubkeep.ini"):
self.config_file = Path.home() / cfg_file
self.config = configparser.ConfigParser()
self.config.read(self.config_file)

def cache_repo(self, name):
"""update repo with name, url and remove_by info."""
if not self.config.has_section(name):
self.config.add_section(name)
self.config.set(
name,
"remove_by",
(
datetime.now()
+ timedelta(minutes=self.config["DEFAULT"].getint("CACHE_DELTA"))
).strftime("%Y%m%d-%H%M%S"),
)
with open(self.config_file, "w") as configfile:
self.config.write(configfile)

def is_repo_stale(self, name):
"""check if the repo is ready to be deleted."""
if self.config.has_section(name):
remove_by = self.config[name].get("remove_by")
remove_by = datetime.strptime(remove_by, "%Y%m%d-%H%M%S")
if remove_by < datetime.now():
return True
else:
return False
else:
return False


def init_dir(home_dir) -> Path:
"""create a dir to save the downloaded files."""
home_dir.mkdir(parents=True, exist_ok=True)
return home_dir
45 changes: 22 additions & 23 deletions src/github_peek/fetch.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,12 @@
from pathlib import Path
import shutil

from github_peek.logging import logger
from github_peek.config import config
from github_peek.config import EDITORS
from github_peek.utils import fetch_repo
from github_peek.utils import extract


def init_dir(home_dir) -> Path:
"""create a dir to save the downloaded files."""
home_dir.mkdir(parents=True, exist_ok=True)
return home_dir
from .logging import logger
from .config import Config
from .config import EDITORS
from .config import init_dir
from .utils import fetch_repo
from .utils import extract


async def open_editor(editor="vim", path: Path = Path("")):
Expand Down Expand Up @@ -42,32 +37,36 @@ def is_old(config_file: Path) -> bool:
def rm_stored_repos(home_dir):
logger.info("removing cached dir: {}".format(home_dir))
shutil.rmtree(home_dir, ignore_errors=True)
os.remove(Path.home() / ".githubkeep.conf")


async def peek_repo(repo: str, caching=True):
config_file = config(".githubkeep.conf")
home_dir = Path.home() / ".githubkeep"
tar_dirs = init_dir(home_dir / "tars")
repo_dir = init_dir(home_dir / "repos" / repo)

await open_editor(path=repo_dir)
if not (os.listdir(repo_dir) or caching):
parsed_config = Config(".githubkeep.ini")
cache_dir = Path.home() / ".githubkeep"
repo_dir = init_dir(cache_dir / "repos" / repo)
if os.path.isdir(repo_dir) and os.listdir(repo_dir):
await open_editor(path=repo_dir)
else:
parsed_config = Config(".githubkeep.ini")
tar_dirs = init_dir(cache_dir / "tars")
logger.info("fetching repo: {}".format(repo))
parsed_config.config.remove_section(repo)
parsed_config.cache_repo(repo)
repo_name = await fetch_repo(repo, tar_dirs)
logger.info("extracting repo: {} to {}".format(repo_name, repo_dir))
await extract(repo_name, repo_dir)
if is_old(config_file):
rm_stored_repos(home_dir)
await open_editor(path=repo_dir)
if parsed_config.is_repo_stale(repo):
rm_stored_repos(cache_dir)
parsed_config.config.remove_section(repo)


# open editor first
# download readme from cdn to the dir in which editor is openend
# extract files to the same dir

# use gitlab api to clone
# types
# profile and imporve loading time


def main(repo="rahulunair/cloudstore"):
loop = asyncio.get_event_loop()
loop.run_until_complete(peek_repo(repo))
5 changes: 3 additions & 2 deletions src/github_peek/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
import aiofiles
import aiohttp

from github_keep.config import GITHUB_API
from github_keep.logging import logger
from .config import GITHUB_API
from .logging import logger


async def make_repo_url(name: str) -> str:
Expand All @@ -16,6 +16,7 @@ async def make_repo_url(name: str) -> str:
url = GITHUB_API.format(owner=owner, repo=repo)
return url


async def fetch_repo(name: str = "", tar_dirs: Path = Path("")):
"""fetch a remote repo."""
repo_url = await make_repo_url(name)
Expand Down

0 comments on commit fa9b22a

Please sign in to comment.