Skip to content

Commit 582ba80

Browse files
committed
better search results in terminal
1 parent 52e41f6 commit 582ba80

File tree

9 files changed

+187
-49
lines changed

9 files changed

+187
-49
lines changed

dataherb/cmd/configs.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,3 @@ def load_dataherb_config(config_path=None, no_config_error=True):
4848
conf = {}
4949

5050
return conf
51-
52-
53-

dataherb/cmd/search.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
from rich.table import Table
2+
from rich.tree import Tree
3+
from rich.panel import Panel
4+
5+
6+
class HerbTable:
7+
"""Format search result
8+
9+
A flora search result has the following structure:
10+
```
11+
"""
12+
13+
def __init__(self, herb):
14+
self.herb = herb
15+
16+
def panel(self):
17+
18+
self.table()
19+
self.resource_tree()
20+
21+
def table(self):
22+
"""Summary Table"""
23+
table = Table(title=f"DataHerb: {self.herb.name}", show_lines=True)
24+
25+
table.add_column("key", justify="right", style="cyan", no_wrap=False)
26+
table.add_column("value", style="magenta", no_wrap=False)
27+
28+
table.add_row(f"ID", f"{self.herb.id}")
29+
table.add_row(f"Name", f"{self.herb.name}")
30+
table.add_row(f"Source", f"{self.herb.source}")
31+
table.add_row(f"Description", f"{self.herb.description}")
32+
table.add_row(f"URI", f"{self.herb.uri}")
33+
table.add_row(f"Metadata", f"{self.herb.metadata_uri}")
34+
35+
pl = Panel(table, title=f"Summary of {self.herb.id}")
36+
37+
return pl
38+
39+
def resource_tree(self):
40+
"""Show list of resources"""
41+
42+
tree = Tree(f"{self.herb.id}")
43+
for r in self.herb.resources:
44+
tree.add(f'{r.descriptor.get("path")}')
45+
46+
pl = Panel(tree, title=f"Resources of {self.herb.id}")
47+
48+
return pl

dataherb/cmd/sync_git.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,9 @@ def upload_dataset_to_git(source, target, experimental=False):
3838
f"Please go to {source} and sync your git repository to {target} manually.\n"
3939
)
4040
if is_git_initialized:
41-
text += (
42-
f"Note: simply add, commit and push."
43-
)
41+
text += f"Note: simply add, commit and push."
4442
else:
45-
text += (
46-
f"Note: git init your repo, commit, add remote {target}, and push."
47-
)
43+
text += f"Note: git init your repo, commit, add remote {target}, and push."
4844
click.echo(text)
4945
else:
5046
if is_git_initialized:
@@ -53,20 +49,23 @@ def upload_dataset_to_git(source, target, experimental=False):
5349
repo.index.commit("created datset: added dataherb.json")
5450

5551
if len(repo.remotes) == 0:
56-
origin = repo.create_remote('origin', target)
52+
origin = repo.create_remote("origin", target)
5753
assert origin.exists()
5854
origin.fetch()
59-
repo.create_head('master', origin.refs.master).set_tracking_branch(origin.refs.master).checkout()
55+
repo.create_head("master", origin.refs.master).set_tracking_branch(
56+
origin.refs.master
57+
).checkout()
6058
origin.push()
6159
else:
6260
repo.git.push()
6361
else:
6462
repo = git.Repo.init(source)
6563
repo.git.add(["*"])
6664
repo.index.commit("initial commit")
67-
origin = repo.create_remote('origin', target)
65+
origin = repo.create_remote("origin", target)
6866
assert origin.exists()
6967
origin.fetch()
70-
repo.create_head('master', origin.refs.master).set_tracking_branch(origin.refs.master).checkout()
68+
repo.create_head("master", origin.refs.master).set_tracking_branch(
69+
origin.refs.master
70+
).checkout()
7171
origin.push()
72-

dataherb/command.py

Lines changed: 102 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
11
import json
2-
import os, sys
2+
import os
3+
import sys
34
from pathlib import Path
45

56
import click
6-
from rich.console import Console
77
import git
8-
from datapackage import Package
98
import inquirer
9+
from datapackage import Package
1010
from loguru import logger
1111
from mkdocs.commands.serve import serve as _serve
12+
from rich.console import Console
1213

1314
from dataherb.cmd.create import describe_dataset
15+
from dataherb.cmd.search import HerbTable
1416
from dataherb.cmd.sync_git import upload_dataset_to_git
1517
from dataherb.cmd.sync_s3 import upload_dataset_to_s3
1618
from dataherb.core.base import Herb
@@ -39,8 +41,15 @@ def dataherb(ctx):
3941

4042

4143
@dataherb.command()
42-
@click.option('--show/--no-show', '-s/ ', default=False, help="Show the current configuration")
43-
@click.option('--locate/--no-locate', '-l/ ', default=False, help="Locate the folder that contains the configuration")
44+
@click.option(
45+
"--show/--no-show", "-s/ ", default=False, help="Show the current configuration"
46+
)
47+
@click.option(
48+
"--locate/--no-locate",
49+
"-l/ ",
50+
default=False,
51+
help="Locate the folder that contains the configuration",
52+
)
4453
def configure(show, locate):
4554
"""
4655
Configure dataherb; inspect, or lcoate the current configurations.
@@ -95,36 +104,42 @@ def configure(show, locate):
95104
with open(config_path, "w") as f:
96105
json.dump(config, f, indent=4)
97106

98-
click.secho(
99-
f"The dataherb config has been saved to {config_path}!", fg="green"
100-
)
107+
click.secho(f"The dataherb config has been saved to {config_path}!", fg="green")
101108
else:
102109
if not config_path.exists():
103110
click.secho(f"Config file ({config_path}) doesn't exist.", fg="red")
104111
else:
105112
c = Config()
106113
click.secho(f"The current config for dataherb is:")
107-
click.secho(json.dumps(c.config, indent=2, sort_keys=True, ensure_ascii=False))
114+
click.secho(
115+
json.dumps(c.config, indent=2, sort_keys=True, ensure_ascii=False)
116+
)
108117
click.secho(f"The above config is extracted from {config_path}")
109118

110119
if locate:
111120
click.launch(str(config_path.parent))
112121

113122

114-
115123
@dataherb.command()
116-
@click.argument("keywords", required=False)
124+
@click.option(
125+
"--flora",
126+
"-f",
127+
default=None,
128+
help="Path to the flora file; Defaults to the default flora in the configuration.",
129+
)
117130
@click.option("--id", "-i", required=False, help="The id of the dataset to describe.")
118-
@click.option("--flora", "-f", default=None, help="Path to the flora file; Defaults to the default flora in the configuration.")
119-
def search(flora, id=None, keywords=None):
131+
@click.argument("keywords", required=False)
132+
@click.option(
133+
"--full/--summary", default=False, help="Whether to show the full json result"
134+
)
135+
def search(flora, id, keywords, full):
120136
"""
121137
search datasets on DataHerb by keywords or id
122138
"""
123139
if flora is None:
124140
c = Config()
125141
flora = c.flora_path
126142

127-
SHOW_KEYS = ["name", "description", "contributors"]
128143
fl = Flora(flora=flora)
129144
if not id:
130145
click.echo("Searching Herbs in DataHerb Flora ...")
@@ -134,25 +149,63 @@ def search(flora, id=None, keywords=None):
134149
click.echo(f"Could not find dataset related to {keywords}")
135150
else:
136151
for result in results:
152+
result_herb = result.get("herb")
137153
result_metadata = result.get("herb").metadata
138-
click.echo(f'DataHerb ID: {result_metadata.get("id")}')
139-
click.echo(result_metadata)
154+
if not full:
155+
ht = HerbTable(result_herb)
156+
console.rule(title=f"{result_herb.id}", characters="||")
157+
console.print(ht.table())
158+
console.print(ht.resource_tree())
159+
else:
160+
console.rule(title=f"{result_herb.id}", characters="||")
161+
click.secho(f"DataHerb ID: {result_herb.id}")
162+
click.echo(json.dumps(result_metadata, indent=2, sort_keys=True))
140163
else:
141164
click.echo(f"Fetching Herbs {id} in DataHerb Flora ...")
142165
result = fl.herb(id)
143166
if not result:
144167
click.echo(f"Could not find dataset with id {id}")
145168
else:
146169
result_metadata = result.metadata
147-
click.echo(f'DataHerb ID: {result_metadata.get("id")}')
148-
click.echo(result_metadata)
170+
171+
if not full:
172+
ht = HerbTable(result)
173+
console.rule(title=f"{result.id}", characters="||")
174+
console.print(ht.table())
175+
console.print(ht.resource_tree())
176+
else:
177+
console.rule(title=f"{result.id}", characters="||")
178+
click.secho(f"DataHerb ID: {result.id}")
179+
click.echo(json.dumps(result_metadata, indent=2, sort_keys=True))
149180

150181

151182
@dataherb.command()
152-
@click.option("--flora", "-f", default=None, help="Specify the path to the flora; defaults to default flora in configuration.")
153-
@click.option("--workdir", "-w", default=None, help="Specify the path to the work directory; defaults to the workdir in configuration.")
154-
@click.option("--dev_addr", "-a", default="localhost:52125", metavar="<IP:PORT>", help="Specify the address of the dev server; defaults to localhost:52125")
155-
@click.option("--recreate", "-r", default=False, required=False, help="Whether to recreate the website. Recreation will delete all the current generated pages and rebuild the whole website.")
183+
@click.option(
184+
"--flora",
185+
"-f",
186+
default=None,
187+
help="Specify the path to the flora; defaults to default flora in configuration.",
188+
)
189+
@click.option(
190+
"--workdir",
191+
"-w",
192+
default=None,
193+
help="Specify the path to the work directory; defaults to the workdir in configuration.",
194+
)
195+
@click.option(
196+
"--dev_addr",
197+
"-a",
198+
default="localhost:52125",
199+
metavar="<IP:PORT>",
200+
help="Specify the address of the dev server; defaults to localhost:52125",
201+
)
202+
@click.option(
203+
"--recreate",
204+
"-r",
205+
default=False,
206+
required=False,
207+
help="Whether to recreate the website. Recreation will delete all the current generated pages and rebuild the whole website.",
208+
)
156209
def serve(flora, workdir, dev_addr, recreate):
157210
"""
158211
create a dataherb server and view the flora in your browser
@@ -179,8 +232,18 @@ def serve(flora, workdir, dev_addr, recreate):
179232

180233
@dataherb.command()
181234
@click.argument("id", required=True)
182-
@click.option("--flora", "-f", default=None, help="Specify the path to the flora; defaults to default flora in configuration.")
183-
@click.option("--workdir", "-w", default=None, help="Specify the path to the work directory; defaults to the workdir in configuration.")
235+
@click.option(
236+
"--flora",
237+
"-f",
238+
default=None,
239+
help="Specify the path to the flora; defaults to default flora in configuration.",
240+
)
241+
@click.option(
242+
"--workdir",
243+
"-w",
244+
default=None,
245+
help="Specify the path to the work directory; defaults to the workdir in configuration.",
246+
)
184247
def download(id, flora, workdir):
185248
"""
186249
Download dataset using id
@@ -229,7 +292,12 @@ def download(id, flora, workdir):
229292
"A dataherb.json file will be created right here.\n"
230293
"Are you sure this is the correct path?"
231294
)
232-
@click.option("--flora", "-f", default=None, help="Specify the path to the flora; defaults to default flora in configuration.")
295+
@click.option(
296+
"--flora",
297+
"-f",
298+
default=None,
299+
help="Specify the path to the flora; defaults to default flora in configuration.",
300+
)
233301
def create(flora):
234302
"""
235303
creates metadata for current dataset
@@ -266,7 +334,9 @@ def create(flora):
266334
md.metadata.update(pkg_descriptor)
267335

268336
if (Path(__CWD__) / "dataherb.json").exists():
269-
is_overwrite = click.confirm("Replace the current dataherb.json file?", default=False)
337+
is_overwrite = click.confirm(
338+
"Replace the current dataherb.json file?", default=False
339+
)
270340
if is_overwrite:
271341
md.create(overwrite=is_overwrite)
272342

@@ -292,7 +362,12 @@ def create(flora):
292362

293363

294364
@dataherb.command()
295-
@click.option("--flora", "-f", default=None, help="Specify the path to the flora; defaults to default flora in configuration.")
365+
@click.option(
366+
"--flora",
367+
"-f",
368+
default=None,
369+
help="Specify the path to the flora; defaults to default flora in configuration.",
370+
)
296371
@click.argument("herb_id", required=True)
297372
def remove(flora, herb_id):
298373
"""

dataherb/core/base.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,12 @@ def _from_meta_dict(self, meta_dict):
6262
"""Build properties from meta dict"""
6363
self.name = meta_dict.get("name")
6464
self.description = meta_dict.get("description")
65-
self.repository = meta_dict.get("repository")
65+
self.repository = meta_dict.get("repository") # Deprecated
6666
self.id = meta_dict.get("id")
6767

6868
self.source = meta_dict.get("source")
6969
self.metadata_uri = meta_dict.get("metadata_uri")
70+
self.uri = meta_dict.get("uri")
7071
self.datapackage = Package(meta_dict.get("datapackage"))
7172
if not self.datapackage:
7273
self.update_datapackage()

dataherb/parse/model_json.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,15 +62,16 @@ def create(self, overwrite=False):
6262

6363
metadata_file = self.metadata_file
6464

65-
6665
if os.path.isfile(os.path.join(dataherb_folder, metadata_file)):
6766
if not overwrite:
6867
logger.error(
6968
f"File {os.path.join(dataherb_folder, metadata_file)} already exists!"
7069
)
7170
raise SystemExit
7271
else:
73-
logger.debug(f"Will overwrite {os.path.join(dataherb_folder, metadata_file)}")
72+
logger.debug(
73+
f"Will overwrite {os.path.join(dataherb_folder, metadata_file)}"
74+
)
7475

7576
with open(os.path.join(dataherb_folder, metadata_file), "w") as fp:
7677
documents = json.dump(self.metadata, fp, indent=4)

dataherb/utils/configs.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88

99

1010
class Config:
11-
"""Config system for Dataherb
12-
"""
11+
"""Config system for Dataherb"""
12+
1313
def __init__(self, config_path=None, no_config_error=False):
1414

1515
self.config_path = config_path
@@ -81,7 +81,9 @@ def workdir(self):
8181

8282
@property
8383
def flora_path(self):
84-
return self._flora_path(self.config.get("default", {}).get("flora"), self.config["workdir"])
84+
return self._flora_path(
85+
self.config.get("default", {}).get("flora"), self.config["workdir"]
86+
)
8587

8688
@property
8789
def flora(self):
@@ -94,4 +96,4 @@ def flora(self):
9496
print(c.config)
9597
print(c.flora_path)
9698
print(c.workdir)
97-
print(c.flora)
99+
print(c.flora)
225 KB
Loading

0 commit comments

Comments
 (0)