Skip to content

Commit

Permalink
123 better help info (#124)
Browse files Browse the repository at this point in the history
obar1 authored Sep 13, 2024
1 parent 241cd37 commit 202301e
Showing 29 changed files with 237 additions and 512 deletions.
7 changes: 3 additions & 4 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -14,15 +14,14 @@ venv/
# idea
.idea/**

# test related
# demo
0to100**/
978*/
0*/
map.md
repo/
toc*.md
*.yaml
safaribooks/
*.yaml
toc.md

# pip install
build
Binary file removed 50a86373-910b-4a12-85ef-251b6d4f08f0.png
Binary file not shown.
Binary file removed 9b873c30-eccb-4c17-9d36-1c302060f5c3.png
Binary file not shown.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -5,7 +5,7 @@ test:
python -m pytest zero_to_one_hundred

testint:
bash demo.sh 0to100_zt && bash demo.sh 0to100_sb
bash demo.sh zt && bash demo.sh sb

format:
black zero_to_one_hundred
79 changes: 36 additions & 43 deletions README.md
Original file line number Diff line number Diff line change
@@ -5,7 +5,7 @@
| [![Quality gate](https://sonarcloud.io/api/project_badges/quality_gate?project=obar1_0to100)](https://sonarcloud.io/summary/new_code?id=obar1_0to100) | [![Makefile CI](https://github.com/obar1/0to100/actions/workflows/makefile.yml/badge.svg)](https://github.com/obar1/0to100/actions/workflows/makefile.yml) |

We read training material from the web and learn from it by doing, but how do we keep that a bit organized? I came up with an idea: this small tool.
Given a 'url', it creates the entry in a markdown map and a folder and links them; in this way, you can easily jump between different sections inside your preferred ide. As you expand the map with new contents, you build some reference material, keep it local all the time, and searchable all the time on your daily coding.
Given a 'url', it creates the entry in a markdown map and a folder and links them; in this way, you can easily jump between different sections inside your preferred ide. As you expand the map with new contents, you build some reference material, keep it local all the time, and searchable all the time on your daily coding and use it to fee your local `llm` :).

## quick demo

@@ -16,27 +16,40 @@ Given a 'url', it creates the entry in a markdown map and a folder and links the
just open this repo in your GitHub Codespace and run the demo as:

```bash
bash demo.sh 0to100_zt
bash demo.sh zt
```

![](termtosvg_0oihyn7a.svg)
![](2dc4491c-fa27-4c5e-bd0c-71951b3ef0e5.png)
[here](./toc_zt.md)

```bash
bash demo.sh 0to100_sb
bash demo.sh sb
```

![](termtosvg_9evceaqa.svg)

![](z05502bb-4b90-422f-9624-568d9f02cd01.png)
[here](./toc_sb.md)


## oto100

0 to 100 ... learn anything from webresources (and not)
0 to 100 ... learn anything from the web

current commands:
commands:

```
['create_section', 'done_section', 'refresh_map', 'refresh_links', 'help']
create_section = create a new section
section=https://www.cloudskillsboost.google/paths/16
./main.py zt create_section "$section"
done_section = tag a section as done
section=https://www.cloudskillsboost.google/paths/16
./main.py zt done_section "$section"
refresh_map = refresh the section map
./main.py zt refresh_map
refresh_links = refresh links to sections in the readme.md(s)
./main.py zt refresh_links
```

> tip
@@ -57,9 +70,9 @@ ex

https://www.cloudskillsboost.google/doc
```
expand the last link to point to the section for the doc - handy as anchor tecnique
expand the last link to point to the section for the doc - handy as anchor technique

### 1st time usage:
### setup and usage:

```bash
# env
@@ -73,31 +86,12 @@ cat map.yaml
export MAP_YAML_PATH=map.yaml
# tip: add it to .bash_rc etc or some shell script

```

![](ab67dd2b-7c12-4cdf-a7a5-f773c2b67919.png)

```bash
chmod +x *.py
# run main
./main.py zt help
```

![](50a86373-910b-4a12-85ef-251b6d4f08f0.png)

### daily usage:

- create new section

```bash
url=https://cloud.google.com/docs
./main.py zt create_section $url

url=https://cloud.google.com/help
./main.py zt create_section $url
#...etc
```

![](9b873c30-eccb-4c17-9d36-1c302060f5c3.png)


## oto100 safari books :construction:

@@ -108,10 +102,14 @@ same as above but it can use some external lib to grab epub from oreilly
current commands:

```
['snatch_book', 'refresh_toc', 'help']
snatch_book = snatch a book from safari
./main.py sb snatch_book https://learning.oreilly.com/library/view/rewire-your-brain/9781119895947
refresh_toc = refresh the toc with al the books info
./main.py sb refresh_toc
```

### 0th time usage:
### setup and usage:

> use what you prefer to grab epub/pdf from oreilly
check this
@@ -120,8 +118,6 @@ or just save as pdf section by section with this
https://chromewebstore.google.com/detail/reader-view/ecabifbgmdmgdllomnfinbmaellmclnh


### 1st time usage:

```bash
# env
python -m venv .venv
@@ -157,7 +153,6 @@ chmod +x *.py

![](63fd79b5-ad41-45fd-a2dc-367f317bcc0c.png)

### daily usage:

- create new meta-book

@@ -170,24 +165,22 @@ and you have a `toc.md` for free to use as your index (bookmark it)

> as I use myself Lorenzo's great utility `safaribooks` I added some code to convert the downloaded epub contents into a related pdf and split that in chunks so I can easily use it on ipad or better remarkable for studying and later sync back in a repo for hands-on code... they call that **learning by doing** 🖖🏻
example:
![](2dc4491c-fa27-4c5e-bd0c-71951b3ef0e5.png)
![](z05502bb-4b90-422f-9624-568d9f02cd01.png)


### tools
> when you start to have a a few 0to100 based folders
>

[gist to sync multiple 0to100 based repos](https://gist.github.com/obar1/771b1992368262737d9f25fcf17ce1c1)
[gist venv auto activate for 0to100 folders](https://gist.github.com/obar1/212e4c778548f8bcdc6e9c1b05856f3f)

## online example

- 0to100
- zt

https://github.com/obar1/zero2hero

- 0to100sb
- sb
> mostly private contents, `sorry but I don't want to get suited :P`
https://github.com/obar1/0to100.oreilly
Binary file removed ab67dd2b-7c12-4cdf-a7a5-f773c2b67919.png
Binary file not shown.
64 changes: 35 additions & 29 deletions demo.sh
Original file line number Diff line number Diff line change
@@ -4,70 +4,76 @@
function setup {
# set -x
export MAP_YAML_PATH=map.yaml

pip install .
chmod +x main*.py

chmod +x main.py
}
function setup0to100_zt {
function setup_zt {
cp ./zero_to_one_hundred/tests/test_ztoh/resources/gcp_map.yaml map.yaml
}

function setup0to100_sb {
function setup_sb {
cp ./zero_to_one_hundred/tests/tests_sb/resources/map.yaml map.yaml

# safari books from lorenzodifuccia
git clone https://github.com/lorenzodifuccia/safaribooks.git
pip install --quiet -r safaribooks/requirements.txt
}

function 0to100_zt {
function zt {
# 0to100
setup0to100_zt
setup_zt

./main.py zt help
content=$(cat << 'EOF'
content=$(
cat <<'EOF'
https://www.cloudskillsboost.google/0
https://www.cloudskillsboost.google/paths/16
https://www.cloudskillsboost.google/games/4424/labs/28651
https://www.cloudskillsboost.google/course_templates/3
https://www.cloudskillsboost.google/games/4422
https://storage.googleapis.com/cloud-training/cls-html5-courses/T-BQRS-I/M1/index.html
EOF
)
while IFS= read -r section || [[ -n "$section" ]]; do
./main.py zt create_section "$section"
done <<< "$content"
)
while IFS= read -r section || [[ -n "$section" ]]; do
./main.py zt create_section "$section"
done <<<"$content"

echo "# a_custom_header 0" >> 0to100/https§§§www.cloudskillsboost.google§0/readme.md
echo "# a_custom_header 0" >>0to100/https§§§www.cloudskillsboost.google§0/readme.md

./main.py zt done_section "https://www.cloudskillsboost.google/0"
./main.py zt done_section "https://www.cloudskillsboost.google/0"

ls -1R 0to100
cp toc.md toc_0to100.md
cp toc.md toc_zt.md
}

function 0to100_sb {
function sb {
# 0to100 safari books
setup0to100_sb
setup_sb

./main.py sb help

./main.py sb snatch_book https://learning.oreilly.com/course/clean-code-fundamentals/9780134661742
echo 'add any metadata you like'
echo '{"title": "Clean Code Fundamentals"}'> 9780134661742/9780134661742.json
echo '{"title": "Clean Code Fundamentals"}' >9780134661742/9780134661742.json
./main.py sb refresh_toc

./main.py sb snatch_book https://learning.oreilly.com/library/view/rewire-your-brain/9781119895947
echo 'pretend book was read fully and get % calc for free :P'
echo '{"page_curr": "100", "page_tot": "100", "url":"https://www.oreilly.com/library/view/rewire-your-brain/9781119895947"}' > 9781119895947/9781119895947.json
echo '{"page_curr": "100", "page_tot": "100", "url":"https://www.oreilly.com/library/view/rewire-your-brain/9781119895947"}' >9781119895947/9781119895947.json
./main.py sb refresh_toc

ls -1R 978*
cp toc.md toc_0to100_sb.md
cp toc.md toc_sb.md

}

setup
$1
#!/bin/bash

if [ $# -eq 0 ]; then
echo "No arguments were passed: use sb or zt"
else
setup
$1
fi
22 changes: 14 additions & 8 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,37 @@
#!/usr/bin/env python3
# coding: utf-8

from enum import Enum
import sys
import logging

from zero_to_one_hundred.exceptions.errors import UnsupportedOptionError
from zero_to_one_hundred.runner import run_core

from zero_to_one_hundred.validator.validator import Validator

if __name__ == "__main__":
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

err_msg = f'zt or sb available, passed {str(sys.argv)}'
try:
arg1= sys.argv[1]
match arg1:
case 'zt':
from zero_to_one_hundred.factories.ztoh_factory_provider import ZTOHFactoryProvider
from zero_to_one_hundred.repository.ztoh_persist_fs import ZTOHPersistFS as persist_fs
from zero_to_one_hundred.repository.ztoh_process_fs import ZTOHProcessFS as process_fs
from zero_to_one_hundred.factories.ztoh_factory_provider import ZTOHFactoryProvider
run_core(sys.argv, ZTOHFactoryProvider(persist_fs, process_fs))
case 'sb':
from zero_to_one_hundred.factories.sb_factory_provider import SBFactoryProvider
from zero_to_one_hundred.repository.sb_persist_fs import SBPersistFS as persist_fs
from zero_to_one_hundred.repository.sb_process_fs import SBProcessFS as process_fs
from zero_to_one_hundred.factories.sb_factory_provider import SBFactoryProvider
run_core(sys.argv, SBFactoryProvider(persist_fs, process_fs))
case _:
raise ValueError(err_msg)
except Exception as e:
logging.info(err_msg)
raise ValueError
except (ValueError,IndexError, TypeError,UnsupportedOptionError):
from zero_to_one_hundred.repository.a_persist_fs import APersistFS as persist_fs
from zero_to_one_hundred.factories.a_factory_provider import AFactoryProvider
run_core(sys.argv, AFactoryProvider(persist_fs))
except Exception as e:
Validator.print_e(e)


7 changes: 4 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env python3

from pathlib import Path
from setuptools import setup
from setuptools import setup, find_packages

directory = Path(__file__).resolve().parent
with open(directory / "README.md", encoding="utf-8") as f:
@@ -12,10 +12,11 @@

setup(
name="0to100",
version="0.4.3",
version="0.5.3",
author="obar1",
packages=find_packages(),
author_email="obar1+gh@pm.me",
description="Simple python tool to learn everything and keep all local.",
description="Simple python tool to learn everything and keep it local.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/obar1/0to100",
129 changes: 0 additions & 129 deletions termtosvg_0oihyn7a.svg

This file was deleted.

182 changes: 0 additions & 182 deletions termtosvg_9evceaqa.svg

This file was deleted.

15 changes: 15 additions & 0 deletions toc_sb.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@

# TOC
## `2` metabook
### 2024/09/13-11:06:37

## legend:

**legend_icons**
`Book` :cyclone:

| ISBN | img | `meta-contents` | `json-contents` | `status` | `icons`
|--- |--- |--- |--- |--- |--- |
|<span style="color:blue">**9780134661742**</span>|![`img`](./9780134661742/9780134661742.png)|[`xyz`](./9780134661742/)|{'isbn': '9780134661742',<br/> 'pages_perc': 'n/a',<br/> 'title': 'Clean Code Fundamentals',<br/> 'url': '> https://learning.oreilly.com/library/9780134661742 <'}|<span style="color:yellow">**WIP**</span>|:cyclone:|
|<span style="color:blue">**9781119895947**</span>|![`img`](./9781119895947/9781119895947.png)|[`xyz`](./9781119895947/)|{'isbn': '9781119895947',<br/> 'page_curr': '100',<br/> 'page_tot': '100',<br/> 'pages_perc': '100.0%',<br/> 'url': '> https://www.oreilly.com/library/view/rewire-your-brain/9781119895947 <'}|<span style="color:green">**DONE**</span>|:cyclone:|
17 changes: 17 additions & 0 deletions toc_zt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# map toc.md, 6

## legend:

**legend_icons**
`Path` :cyclone:
`Lab` :floppy_disk:
`Template` :whale:
`Game` :snake:
`Course` :pushpin:

1. # <https§§§www.cloudskillsboost.google§paths§16> [`here`](./0to100/https§§§www.cloudskillsboost.google§paths§16/readme.md) `wip` :cyclone:
1. # <https§§§www.cloudskillsboost.google§games§4424§labs§28651> [`here`](./0to100/https§§§www.cloudskillsboost.google§games§4424§labs§28651/readme.md) `wip` :floppy_disk: :snake:
1. # <https§§§www.cloudskillsboost.google§course_templates§3> [`here`](./0to100/https§§§www.cloudskillsboost.google§course_templates§3/readme.md) `wip` :whale: :pushpin:
1. # <https§§§www.cloudskillsboost.google§games§4422> [`here`](./0to100/https§§§www.cloudskillsboost.google§games§4422/readme.md) `wip` :snake:
1. # <https§§§storage.googleapis.com§cloud-training§cls-html5-courses§T-BQRS-I§M1§index.html> [`here`](./0to100/https§§§storage.googleapis.com§cloud-training§cls-html5-courses§T-BQRS-I§M1§index.html/readme.md) `wip` :pushpin:
1. # a_custom_header 0 [`here`](./0to100/https§§§www.cloudskillsboost.google§0/readme.md) `done`
9 changes: 3 additions & 6 deletions zero_to_one_hundred/configs/a_config_map.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
# pylint: disable=W0246
import os
from abc import ABC
from dataclasses import dataclass

from zero_to_one_hundred.exceptions.errors import SomeError
from zero_to_one_hundred.repository.a_persist_fs import APersistFS


class AConfigMap(ABC):
class AConfigMap:
MAP_YAML_PATH = "MAP_YAML_PATH"

@dataclass
@@ -20,14 +19,12 @@ def __init__(self, persist_fs: APersistFS):
self.map_yaml_path = os.getenv(AConfigMap.MAP_YAML_PATH)
if self.map_yaml_path is None:
raise SomeError(
f"map_yaml_path {self.map_yaml_path} is not valid,\nplease set it in the env ex:\n`export MAP_YAML_PATH=map.yaml`"
f"map_yaml_path {self.map_yaml_path} is not valid,\nplease set it in the env ex:\nexport MAP_YAML_PATH=map.yaml"
)
self.persist_fs = persist_fs

def __repr__(self):
return (
f"{AConfigMap.MAP_YAML_PATH} from {self.map_yaml_path} type {self.get_type}"
)
return f"{AConfigMap.MAP_YAML_PATH} from {self.map_yaml_path} type {self.get_type}\nraw data:\n{self.load}"

@property
def load(self):
37 changes: 29 additions & 8 deletions zero_to_one_hundred/factories/a_factory.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,42 @@
from abc import ABC, abstractmethod
from enum import Enum
from typing import Generator

from zero_to_one_hundred.processors.a_processor import AProcessor
from zero_to_one_hundred.processors.help_processor import HelpProcessor
from zero_to_one_hundred.processors.unsupported_processor import UnsupportedProcessor
from zero_to_one_hundred.repository.a_persist_fs import APersistFS


class AFactory(ABC):
class AFactory:
"""AFactory class."""

class SUPPORTED_PROCESSOR(Enum):
help = 1
zt = 1
sb = 2
help = 3

@abstractmethod
def get_processor(self, args) -> Generator[AProcessor, None, None]:
pass
extended_help = """
zt = zero to 100
./main.py zt help
sb = sb to 100
./main.py sb help
help = this :)
./main.py help
"""

def __init__(self, persist_fs: APersistFS):
self.persist_fs = persist_fs

def get_processor(self,args) -> Generator[AProcessor, None, None]:
yield self.help_processor()

def help_processor(self):
return HelpProcessor(
None, self.persist_fs, self.SUPPORTED_PROCESSOR, self.extended_help
)

@staticmethod
def unsupported_processor(cmd):
return UnsupportedProcessor(cmd)
def unsupported_processor(cmd, supp):
return UnsupportedProcessor(cmd, supp)
14 changes: 5 additions & 9 deletions zero_to_one_hundred/factories/a_factory_provider.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
from abc import ABC, abstractmethod

from zero_to_one_hundred.factories.a_factory import AFactory
from zero_to_one_hundred.repository.a_persist_fs import APersistFS


class AFactoryProvider(ABC):
class AFactoryProvider:
"""AFactoryProvider."""

@abstractmethod
def __init__(self, persist_fs: APersistFS, process_fs):
pass
def __init__(self, persist_fs=None, process_fs=None):
self.persist_fs = persist_fs
self.process_fs = process_fs

@abstractmethod
def provide(self) -> None | AFactory:
pass
return AFactory(persist_fs=self.persist_fs)
32 changes: 12 additions & 20 deletions zero_to_one_hundred/factories/sb_factory.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import argparse
from enum import Enum

from zero_to_one_hundred.configs.sb_config_map import SBConfigMap
from zero_to_one_hundred.factories.a_factory import AFactory
from zero_to_one_hundred.processors.help_processor import HelpProcessor
from zero_to_one_hundred.processors.refresh_toc_processor import RefreshTocProcessor
from zero_to_one_hundred.processors.snatch_book_processor import (
SnatchBookProcessor,
)
from zero_to_one_hundred.repository.sb_persist_fs import SBPersistFS
from zero_to_one_hundred.repository.sb_process_fs import SBProcessFS
from zero_to_one_hundred.validator.validator import Validator


class SBFactory(AFactory):
@@ -20,27 +19,23 @@ class SUPPORTED_PROCESSOR(Enum):
refresh_toc = 2
help = 3

extended_help = """
snatch_book = snatch a book from safari
./main.py sb snatch_book https://learning.oreilly.com/library/view/rewire-your-brain/9781119895947
refresh_toc = refresh the toc with al the books info
./main.py sb refresh_toc
"""

def __init__(
self, config_map: SBConfigMap, persist_fs: SBPersistFS, process_fs: SBProcessFS
):
super().__init__(persist_fs=persist_fs)
self.config_map = config_map
self.persist_fs = persist_fs
self.process_fs = process_fs

def get_processor(self, args):
parser = argparse.ArgumentParser(description="Run 0to100_sb.")
valid_cmds = list(p.name for p in self.SUPPORTED_PROCESSOR)
parser.add_argument(
"cmd",
type=str,
help=f'command, must be {" ".join(valid_cmds)}',
choices=valid_cmds,
)
parser.add_argument("p1", type=str, help="arg p1", nargs="?", default=None)

args = parser.parse_args(args[2:])
cmd = args.cmd
p1 = args.p1
cmd, p1 = Validator.validate_args(args)
if cmd == SBFactory.SUPPORTED_PROCESSOR.snatch_book.name:
http_url = p1
yield self.snatch_book_processor(http_url)
@@ -50,7 +45,7 @@ def get_processor(self, args):
elif cmd == SBFactory.SUPPORTED_PROCESSOR.help.name:
yield self.help_processor()
else:
yield self.unsupported_processor(cmd)
yield self.unsupported_processor(cmd, self.SUPPORTED_PROCESSOR)

def snatch_book_processor(self, http_url):
return SnatchBookProcessor(
@@ -59,6 +54,3 @@ def snatch_book_processor(self, http_url):

def refresh_toc_processor(self):
return RefreshTocProcessor(self.config_map, self.persist_fs, self.process_fs)

def help_processor(self):
return HelpProcessor(self.config_map, self.persist_fs, self.SUPPORTED_PROCESSOR)
5 changes: 3 additions & 2 deletions zero_to_one_hundred/factories/sb_factory_provider.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from zero_to_one_hundred.configs.sb_config_map import SAFARI_BOOKS_MAP, SBConfigMap
from zero_to_one_hundred.exceptions.errors import UnsupportedConfigMapError
from zero_to_one_hundred.factories.a_factory_provider import AFactoryProvider
from zero_to_one_hundred.factories.sb_factory import SBFactory
from zero_to_one_hundred.repository.sb_persist_fs import SBPersistFS
@@ -19,4 +18,6 @@ def provide(self) -> SBFactory:
config_map_type = config_map.get_type
if config_map_type == SAFARI_BOOKS_MAP:
return SBFactory(config_map, self.persist_fs, self.process_fs)
raise UnsupportedConfigMapError(config_map_type)
raise NotImplementedError(
f"Expected {config_map_type}, check the files contents of {config_map}"
)
41 changes: 20 additions & 21 deletions zero_to_one_hundred/factories/ztoh_factory.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import argparse
from enum import Enum

from zero_to_one_hundred.configs.ztoh_config_map import ZTOHConfigMap
@@ -7,11 +6,11 @@
CreateSectionProcessor,
)
from zero_to_one_hundred.processors.done_section_processor import DoneSectionProcessor
from zero_to_one_hundred.processors.help_processor import HelpProcessor
from zero_to_one_hundred.processors.refresh_links_processor import RefreshLinksProcessor
from zero_to_one_hundred.processors.refresh_map_processor import RefreshMapProcessor
from zero_to_one_hundred.repository.ztoh_persist_fs import ZTOHPersistFS
from zero_to_one_hundred.repository.ztoh_process_fs import ZTOHProcessFS
from zero_to_one_hundred.validator.validator import Validator


class ZTOHFactory(AFactory):
@@ -24,31 +23,34 @@ class SUPPORTED_PROCESSOR(Enum):
refresh_links = 4
help = 5

extended_help = """
create_section = create a new section
section=https://www.cloudskillsboost.google/paths/16
./main.py zt create_section "$section"
done_section = tag a section as done
section=https://www.cloudskillsboost.google/paths/16
./main.py zt done_section "$section"
refresh_map = refresh the section map
./main.py zt refresh_map
refresh_links = refresh links to sections in the readme.md(s)
./main.py zt refresh_links
"""

def __init__(
self,
config_map: ZTOHConfigMap,
persist_fs: ZTOHPersistFS,
process_fs: ZTOHProcessFS,
):
super().__init__(persist_fs=persist_fs)
self.config_map = config_map
self.persist_fs = persist_fs
self.process_fs = process_fs

def get_processor(self, args):
parser = argparse.ArgumentParser(description="Run 0to100.")
valid_cmds = list(p.name for p in self.SUPPORTED_PROCESSOR)
parser.add_argument(
"cmd",
type=str,
help=f'command, must be {" ".join(valid_cmds)}',
choices=valid_cmds,
)
parser.add_argument("p1", type=str, help="arg p1", nargs="?", default=None)

args = parser.parse_args(args[2:])
cmd = args.cmd
p1 = args.p1

cmd, p1 = Validator.validate_args(args)
if cmd == ZTOHFactory.SUPPORTED_PROCESSOR.create_section.name:
yield self.create_section_processor(p1)
yield self.refresh_map_processor()
@@ -63,7 +65,7 @@ def get_processor(self, args):
elif cmd == ZTOHFactory.SUPPORTED_PROCESSOR.help.name:
yield self.help_processor()
else:
yield self.unsupported_processor(cmd)
yield self.unsupported_processor(cmd, self.SUPPORTED_PROCESSOR)

def create_section_processor(self, http_url):
return CreateSectionProcessor(
@@ -80,6 +82,3 @@ def refresh_map_processor(self):

def refresh_links_processor(self):
return RefreshLinksProcessor(self.config_map, self.persist_fs, self.process_fs)

def help_processor(self):
return HelpProcessor(self.config_map, self.persist_fs, self.SUPPORTED_PROCESSOR)
2 changes: 1 addition & 1 deletion zero_to_one_hundred/factories/ztoh_factory_provider.py
Original file line number Diff line number Diff line change
@@ -19,5 +19,5 @@ def provide(self) -> ZTOHFactory:
if config_map_type == ZTOH_MAP:
return ZTOHFactory(config_map, self.persist_fs, self.process_fs)
raise NotImplementedError(
f"NotImplementedError {config_map_type}, check the files contents of {config_map.map_yaml_path}"
f"Expected {config_map_type}, check the files contents of {config_map}"
)
13 changes: 10 additions & 3 deletions zero_to_one_hundred/processors/help_processor.py
Original file line number Diff line number Diff line change
@@ -7,13 +7,20 @@

class HelpProcessor(AProcessor):
def __init__(
self, config_map: AConfigMap, persist_fs: APersistFS, supported_processor
self,
config_map: AConfigMap,
persist_fs: APersistFS,
supported_processor,
extended_help,
):
self.config_map = config_map
self.persist_fs = persist_fs
self.supported_processor = supported_processor
self.extended_help = extended_help

def process(self):
logging.info(self.persist_fs.get_pkg_info())
logging.info(f"{repr(self.config_map)}")
logging.info([p.name for p in self.supported_processor])
if self.config_map:
logging.info(f"config_map: {repr(self.config_map)}")
logging.info(f"supported: {[s.name for s in self.supported_processor]}")
logging.info(f"extended help: {self.extended_help}")
11 changes: 6 additions & 5 deletions zero_to_one_hundred/processors/unsupported_processor.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import logging

from zero_to_one_hundred.exceptions.errors import UnsupportedOptionError

from zero_to_one_hundred.processors.a_processor import AProcessor
@@ -9,9 +7,12 @@ class UnsupportedProcessor(AProcessor):
"""UnsupportedProcessor:
std UnsupportedProcessor"""

def __init__(self, cmd):
def __init__(self, cmd, supp):
self.cmd = cmd
self.supp = supp

def process(self):
logging.info(f"DDD Unsupported Processor {self.cmd}")
raise UnsupportedOptionError("DDD Unsupported Processor {self.cmd}")
supp_str = "`{}`".format("` `".join([s.name for s in self.supp]))
raise UnsupportedOptionError(
f"Unsupported Processor `{self.cmd}`, supported: {supp_str}"
)
20 changes: 2 additions & 18 deletions zero_to_one_hundred/runner.py
Original file line number Diff line number Diff line change
@@ -2,10 +2,8 @@
from typing import List
from typing import Union, TypeVar

from zero_to_one_hundred.exceptions.errors import SomeError
from zero_to_one_hundred.factories.a_factory import AFactory
from zero_to_one_hundred.factories.a_factory_provider import AFactoryProvider
from zero_to_one_hundred.validator.validator import Validator


def run_core(argv: List[str], factory_provider: AFactoryProvider):
@@ -18,19 +16,5 @@ def run_core(argv: List[str], factory_provider: AFactoryProvider):
"""

T = TypeVar("T", bound=AFactory)
factory: Union[AFactory, T]
try:
factory = factory_provider.provide()
[processor.process() for processor in factory.get_processor(argv) if processor]
except SomeError as e:
Validator.print_e(e)
return
except FileNotFoundError as e:
Validator.print_e(e)
return
except NotImplementedError as e:
Validator.print_e(e)
return
except Exception as e:
Validator.print_e(e)
factory.help_processor().process()
factory: Union[AFactory, T] = factory_provider.provide()
[processor.process() for processor in factory.get_processor(argv) if processor]
1 change: 1 addition & 0 deletions zero_to_one_hundred/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import string
from unittest.mock import patch

import pytest


1 change: 1 addition & 0 deletions zero_to_one_hundred/tests/test_ztoh/test_map.py
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@
from zero_to_one_hundred.models.section import Section
from zero_to_one_hundred.tests.conftest import str_relaxed


# pylint: disable=W0102


9 changes: 1 addition & 8 deletions zero_to_one_hundred/tests/test_ztoh/test_ztoh_config_map.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from zero_to_one_hundred.configs.ztoh_config_map import ZTOH_MAP, ZTOHConfigMap


# pylint: disable=W0621,W0613


@@ -11,14 +12,6 @@ def test_config_map(get_config_map: ZTOHConfigMap):
assert actual.get_legend_type is None


def test__repr__(get_config_map: ZTOHConfigMap, get_map_yaml_path: str):
actual = get_config_map
assert (
repr(actual)
== f"MAP_YAML_PATH from {get_map_yaml_path} type {get_config_map.get_type}"
)


def test_gcp_config_map(get_gcp_config_map: ZTOHConfigMap):
actual = get_gcp_config_map
assert actual.get_type == ZTOH_MAP
2 changes: 1 addition & 1 deletion zero_to_one_hundred/tests/tests_sb/resources/map.yaml
Original file line number Diff line number Diff line change
@@ -5,7 +5,7 @@ configs:
download_books: false
oreilly_username: "username"
oreilly_userpassword: "userpassword"
split_pdf_pages: 100
split_pdf_pages: 0
legend:
type: "sb"
icons:
10 changes: 1 addition & 9 deletions zero_to_one_hundred/tests/tests_sb/test_sb_config_map.py
Original file line number Diff line number Diff line change
@@ -12,13 +12,5 @@ def test_provide__pass(get_config_map: SBConfigMap):
assert actual.get_oreilly_username is not None
assert actual.get_oreilly_userpassword is not None
assert actual.get_oreilly_userpassword is not None
assert actual.get_split_pdf_pages == 100
assert actual.get_split_pdf_pages == 0
assert actual.get_download_books is False


def test__repr__(get_config_map: SBConfigMap, get_map_yaml_path: str):
actual = get_config_map
assert (
repr(actual)
== f"MAP_YAML_PATH from {get_map_yaml_path} type {get_config_map.get_type}"
)
18 changes: 16 additions & 2 deletions zero_to_one_hundred/validator/validator.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import argparse
import logging
import traceback
import re

import traceback

from zero_to_one_hundred.exceptions.errors import NotURLFormatError

@@ -17,3 +17,17 @@ def is_valid_http(cls, url: str):
def print_e(cls, e: Exception):
logging.exception(traceback.format_exc())
logging.exception(f"#DDD issue with {e}")

@classmethod
def validate_args(cls, args):
parser = argparse.ArgumentParser()
parser.add_argument("cmd", type=str, nargs="?", default=None)
parser.add_argument("p1", type=str, nargs="?", default=None)
try:
args = parser.parse_args(args[2:]) # skip fn
cmd = args.cmd
p1 = args.p1
return cmd, p1
except Exception:
pass
return None, None

0 comments on commit 202301e

Please sign in to comment.