Skip to content

Commit 0701711

Browse files
committed
added remove function
1 parent a213c30 commit 0701711

File tree

14 files changed

+366
-59
lines changed

14 files changed

+366
-59
lines changed

dataherb/cmd/configs.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
logger.remove()
77
logger.add(sys.stderr, level="INFO", enqueue=True)
88

9-
def load_dataherb_config(config_path=None):
9+
10+
def load_dataherb_config(config_path=None, no_config_error=True):
1011
"""Loads the dataherb config file.
1112
1213
Load the content from the specified file as the config. The config file has to be json.
@@ -17,10 +18,14 @@ def load_dataherb_config(config_path=None):
1718
config_path = home / ".dataherb/config.json"
1819

1920
if not config_path.exists():
20-
logger.error(
21-
f"Config file {config_path} does not exist.\n"
22-
f"If this is the first time you use dataherb, please run `dataherb configure` to config dataherb."
23-
)
21+
if no_config_error:
22+
logger.error(
23+
f"Config file {config_path} does not exist.\n"
24+
f"If this is the first time you use dataherb, please run `dataherb configure` to config dataherb."
25+
)
26+
else:
27+
pass
28+
return {}
2429

2530
logger.debug(f"Using {config_path} as config file for dataherb")
2631
try:

dataherb/cmd/create.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
logger.remove()
99
logger.add(sys.stderr, level="INFO", enqueue=True)
1010

11+
1112
def describe_file(file):
1213
"""
1314
describe_file [summary]
@@ -89,6 +90,7 @@ def describe_dataset():
8990
meta = {
9091
"source": answers.get("source"),
9192
"name": answers.get("name", ""),
93+
"id": answers["id"],
9294
"description": answers.get("description", ""),
9395
"uri": answers.get("uri", ""),
9496
"metadata_uri": metadata_uri,

dataherb/command.py

Lines changed: 69 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,14 @@ def configure():
4444
config_path = home / ".dataherb/config.json"
4545

4646
if config_path.exists():
47-
is_overwite = click.confirm(f"Config file ({config_path}) already exists. Overwrite?", default=False)
47+
is_overwite = click.confirm(
48+
click.style(
49+
f"Config file ({config_path}) already exists. Overwrite?", fg="red"
50+
),
51+
default=False,
52+
)
4853
if is_overwite:
49-
click.echo("Overwriting config file...")
54+
click.echo(click.style("Overwriting config file...", fg="red"))
5055
else:
5156
click.echo("Skipping...")
5257
sys.exit(0)
@@ -62,35 +67,36 @@ def configure():
6267
"workdir",
6368
message="Where should I put all the datasets and flora database? An empty folder is recommended.",
6469
# path_type=inquirer.Path.DIRECTORY,
65-
normalize_to_absolute_path=True
70+
normalize_to_absolute_path=True,
6671
),
6772
inquirer.Text(
6873
"default_flora",
6974
message="How would you name the default flora? Please keep the default value if this is not clear to you.",
70-
default="flora"
71-
)
75+
default="flora",
76+
),
7277
]
7378

7479
answers = inquirer.prompt(questions)
7580

7681
config = {
7782
"workdir": answers.get("workdir"),
78-
"default": {
79-
"flora": answers.get("default_flora")
80-
}
83+
"default": {"flora": answers.get("default_flora")},
8184
}
8285

8386
logger.debug(f"config: {config}")
8487

8588
with open(config_path, "w") as f:
8689
json.dump(config, f, indent=4)
8790

88-
click.echo(f"The dataherb config has been saved to {config_path}!")
89-
91+
click.echo(
92+
click.style(f"The dataherb config has been saved to {config_path}!", fg="green")
93+
)
9094

9195

92-
CONFIG = load_dataherb_config()
96+
CONFIG = load_dataherb_config(no_config_error=False)
9397
logger.debug(CONFIG)
98+
if not CONFIG:
99+
click.echo("No config file found. Please run 'dataherb configure' to create one.")
94100
WD = CONFIG.get("workdir", ".")
95101
which_flora = CONFIG.get("default", {}).get("flora")
96102
if which_flora:
@@ -100,8 +106,6 @@ def configure():
100106
raise Exception(f"flora config {which_flora} does not exist")
101107

102108

103-
104-
105109
@dataherb.command()
106110
@click.argument("keywords", required=False)
107111
@click.option("--id", "-i", required=False)
@@ -138,21 +142,24 @@ def search(flora, id=None, keywords=None):
138142
@click.option("--flora", "-f", default=which_flora)
139143
@click.option("--workdir", "-w", default=WD, required=True)
140144
@click.option("--dev_addr", "-a", metavar="<IP:PORT>")
141-
def serve(flora, workdir, dev_addr):
145+
@click.option("--recreate", "-r", default=False, required=False)
146+
def serve(flora, workdir, dev_addr, recreate):
142147
fl = Flora(flora=flora)
143148
mk = SaveMkDocs(flora=fl, workdir=workdir)
144-
mk.save_all()
149+
mk.save_all(recreate=recreate)
145150

146-
mkdocs_config = str(Path(WD) / "serve" / "mkdocs.yml")
151+
mkdocs_config = str(Path(workdir) / "serve" / "mkdocs.yml")
147152

148153
click.echo("Open http://localhost:8000")
154+
click.launch("http://localhost:8000")
149155
_serve(config_file=mkdocs_config, dev_addr=dev_addr)
150156

151157

152158
@dataherb.command()
153159
@click.argument("id", required=True)
154160
@click.option("--flora", "-f", default=which_flora)
155-
def download(id, flora):
161+
@click.option("--workdir", "-w", default=WD, required=True)
162+
def download(id, flora, workdir):
156163
"""
157164
download dataset using id
158165
"""
@@ -167,7 +174,7 @@ def download(id, flora):
167174
click.echo(f'Downloading DataHerb ID: {result_metadata.get("id")}')
168175
result_uri = result_metadata.get("uri")
169176
result_id = result_metadata.get("id")
170-
dest_folder = str(Path(WD) / result_id)
177+
dest_folder = str(Path(workdir) / result_id)
171178
if os.path.exists(dest_folder):
172179
click.echo(f"Can not download dataset to {dest_folder}: folder exists.\n")
173180

@@ -225,18 +232,53 @@ def create(flora):
225232

226233
md.metadata.update(pkg_descriptor)
227234

228-
md.create()
229-
230-
click.echo(
231-
"The dataherb.json file has been created inside \n"
232-
f"{__CWD__}\n"
233-
"Please review the dataherb.json file and update other necessary fields."
234-
)
235+
if (Path(__CWD__) / "dataherb.json").exists():
236+
is_overwrite = click.confirm("Replace the current dataherb.json file?", default=False)
237+
if is_overwrite:
238+
md.create(overwrite=is_overwrite)
235239

236-
hb = Herb(md.metadata)
240+
click.echo(
241+
f"The dataherb.json file in folder {__CWD__} has been replaced. \n"
242+
"Please review the dataherb.json file and update other necessary fields."
243+
)
244+
else:
245+
click.echo("We did nothing.")
246+
sys.exit()
247+
else:
248+
md.create()
249+
click.echo(
250+
"The dataherb.json file has been created inside \n"
251+
f"{__CWD__}\n"
252+
"Please review the dataherb.json file and update other necessary fields."
253+
)
254+
255+
hb = Herb(md.metadata, with_resources=False)
237256
fl.add(hb)
238257

239-
click.echo(f"Added {hb.metadata['id']} into the flora.")
258+
click.echo(f"Added {hb.id} into the flora.")
259+
260+
261+
@dataherb.command()
262+
@click.option("--flora", "-f", default=which_flora)
263+
@click.argument("herb_id", required=True)
264+
def remove(flora, herb_id):
265+
"""
266+
remove herb from flora
267+
"""
268+
269+
fl = Flora(flora=flora)
270+
herb = fl.herb(herb_id)
271+
if not herb:
272+
click.echo(click.style(f"Could not find herb with id {herb_id}", fg="red"))
273+
click.echo("We did nothing.")
274+
sys.exit()
275+
276+
to_remove = click.confirm(f"Remove {herb_id} from the flora?", default=False)
277+
if to_remove:
278+
fl.remove(herb_id)
279+
click.echo(f"Removed {herb_id} into the flora.")
280+
else:
281+
click.echo("We did nothing.")
240282

241283

242284
@dataherb.command()
@@ -329,10 +371,6 @@ def echo_summary(key, value_dict, bg=None, fg=None):
329371
)
330372

331373

332-
333-
334-
335-
336374
if __name__ == "__main__":
337375
fl = Flora()
338376
pass

dataherb/core/base.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ class Herb(object):
2121
Herb is a collection of the dataset.
2222
"""
2323

24-
def __init__(self, meta_dict, base_path=None):
24+
def __init__(self, meta_dict, base_path=None, with_resources=True):
2525
"""
2626
:param herb_meta_json: the dictionary that specifies the herb
2727
:type herb_meta_json: dict
@@ -34,6 +34,8 @@ def __init__(self, meta_dict, base_path=None):
3434
if isinstance(self.base_path, str):
3535
self.base_path = Path(self.base_path)
3636

37+
self.with_resources = with_resources
38+
3739
if isinstance(meta_dict, dict):
3840
self.herb_meta_json = meta_dict
3941
elif isinstance(meta_dict, MetaData):
@@ -69,10 +71,11 @@ def _from_meta_dict(self, meta_dict):
6971
if not self.datapackage:
7072
self.update_datapackage()
7173

72-
self.resources = [
73-
self.get_resource(i, source_only=False)
74-
for i in range(len(self.datapackage.resources))
75-
]
74+
if self.with_resources:
75+
self.resources = [
76+
self.get_resource(i, source_only=False)
77+
for i in range(len(self.datapackage.resources))
78+
]
7679

7780
def get_resource(self, idx=None, path=None, name=None, source_only=True):
7881
if idx is None:
@@ -98,7 +101,7 @@ def get_resource(self, idx=None, path=None, name=None, source_only=True):
98101
)
99102

100103
if self.is_local:
101-
logger.info(
104+
logger.debug(
102105
f"Using local dataset for {self.id}, sync it if you need the updated version."
103106
)
104107
r = self.datapackage.resources[idx]

dataherb/flora.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@
55
from loguru import logger
66

77
from dataherb.core.base import Herb
8-
from dataherb.core.search import \
9-
search_by_ids_in_flora as _search_by_ids_in_flora
10-
from dataherb.core.search import \
11-
search_by_keywords_in_flora as _search_by_keywords_in_flora
8+
from dataherb.core.search import search_by_ids_in_flora as _search_by_ids_in_flora
9+
from dataherb.core.search import (
10+
search_by_keywords_in_flora as _search_by_keywords_in_flora,
11+
)
1212
from dataherb.fetch.remote import get_data_from_url as _get_data_from_url
1313
from dataherb.parse.model_json import MetaData
1414

@@ -87,6 +87,19 @@ def add(self, herb):
8787
self.flora.append(herb)
8888
self.save()
8989

90+
def remove(self, herb_id):
91+
"""
92+
add add a herb to the flora
93+
"""
94+
95+
for id in [i.id for i in self.flora]:
96+
if id == herb_id:
97+
logger.debug(f"found herb id = {herb_id}")
98+
99+
self.flora = [h for h in self.flora if h.id != herb_id]
100+
101+
self.save()
102+
90103
def save(self, path=None):
91104
"""save flora metadata to json file"""
92105

dataherb/parse/model_json.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def load(self):
4646

4747
logger.debug(f"Loaded metadata: {self.metadata}")
4848

49-
def create(self):
49+
def create(self, overwrite=False):
5050
"""creates dataherb.json file"""
5151
# create .dataherb folder
5252
dataherb_folder = self.dataherb_folder
@@ -62,11 +62,15 @@ def create(self):
6262

6363
metadata_file = self.metadata_file
6464

65+
6566
if os.path.isfile(os.path.join(dataherb_folder, metadata_file)):
66-
logger.error(
67-
f"File {os.path.join(dataherb_folder, metadata_file)} already exists!"
68-
)
69-
raise SystemExit
67+
if not overwrite:
68+
logger.error(
69+
f"File {os.path.join(dataherb_folder, metadata_file)} already exists!"
70+
)
71+
raise SystemExit
72+
else:
73+
logger.debug(f"Will overwrite {os.path.join(dataherb_folder, metadata_file)}")
7074

7175
with open(os.path.join(dataherb_folder, metadata_file), "w") as fp:
7276
documents = json.dump(self.metadata, fp, indent=4)
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
title: Home
3+
---
4+
5+
This is the landing page of DataHerb. Please use the search of the sidebar to find view the datasets.
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
site_name: My DataHerb
2+
3+
docs_dir: herbs
4+
5+
theme:
6+
name: "material"
7+
custom_dir: overrides
8+
include_search_page: false
9+
search_index_only: true
10+
11+
language: en
12+
features:
13+
- navigation.sections
14+
- navigation.instant
15+
palette:
16+
- scheme: default
17+
primary: indigo
18+
accent: indigo
19+
toggle:
20+
icon: material/toggle-switch-off-outline
21+
name: Switch to dark mode
22+
- scheme: slate
23+
primary: red
24+
accent: red
25+
toggle:
26+
icon: material/toggle-switch
27+
name: Switch to light mode
28+
29+
30+
31+
32+
markdown_extensions:
33+
- meta
34+
- admonition
35+
36+
plugins:
37+
- search
38+
- macros
39+
40+

0 commit comments

Comments
 (0)