Skip to content

Commit 9f388c1

Browse files
Merge pull request #72 from sleter/master
Controlling output PackageInfo parameters
2 parents 0fb1a55 + 9780720 commit 9f388c1

File tree

13 files changed

+227
-55
lines changed

13 files changed

+227
-55
lines changed

licensecheck/__init__.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from __future__ import annotations
55

66
import argparse
7+
from dataclasses import fields
78
from pathlib import Path
89
from sys import exit as sysexit
910
from sys import stdout
@@ -70,6 +71,11 @@ def cli() -> None:
7071
help="a list of packages to skip (compat=True)",
7172
nargs="+",
7273
)
74+
parser.add_argument(
75+
"--hide-output-parameters",
76+
help="a list of parameters to hide from the produced output",
77+
nargs="+"
78+
)
7379
parser.add_argument(
7480
"--zero",
7581
"-0",
@@ -119,10 +125,19 @@ def cli() -> None:
119125
incompatible = any(not lice.licenseCompat for lice in depsWithLicenses)
120126

121127
# Format the results
128+
hide_output_parameters = list(map(types.ucstr, simpleConf.get("hide_output_parameters", [])))
129+
available_params = [param.name.upper() for param in fields(types.PackageInfo)]
130+
if not all(hop in available_params for hop in hide_output_parameters):
131+
raise ValueError(
132+
f"Invalid parameter(s) in `hide_output_parameters`. "
133+
f"Valid parameters are: {', '.join(available_params)}"
134+
)
122135
if simpleConf.get("format", "simple") in formatter.formatMap:
123136
print(
124137
formatter.formatMap[simpleConf.get("format", "simple")](
125-
myLice, sorted(depsWithLicenses)
138+
myLice,
139+
sorted(depsWithLicenses),
140+
hide_output_parameters,
126141
),
127142
file=textIO,
128143
)

licensecheck/formatter.py

Lines changed: 50 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
- csv
2323
"""
2424
from __future__ import annotations
25+
from collections import OrderedDict
2526

2627
import csv
2728
import json
@@ -56,13 +57,14 @@ def stripAnsi(string: str) -> str:
5657
return re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])").sub("", string)
5758

5859

59-
def ansi(myLice: License, packages: list[PackageInfo]) -> str:
60+
def ansi(myLice: License, packages: list[PackageInfo], hide_parameters: list[str] = []) -> str:
6061
"""Format to ansi.
6162
6263
Args:
6364
----
6465
myLice (License): project license
6566
packages (list[PackageInfo]): list of PackageCompats to format.
67+
hide_parameters (list[str]): list of parameters to ignore in the output.
6668
6769
Returns:
6870
-------
@@ -92,41 +94,55 @@ def ansi(myLice: License, packages: list[PackageInfo]) -> str:
9294
console.print(table)
9395

9496
table = Table(title="\nList Of Packages")
95-
table.add_column("Compatible", style="cyan")
96-
table.add_column("Package", style="magenta")
97-
table.add_column("License(s)", style="magenta")
97+
if licensecompat_bool := not "LICENSECOMPAT" in hide_parameters:
98+
table.add_column("Compatible", style="cyan")
99+
if name_bool := not "NAME" in hide_parameters:
100+
table.add_column("Package", style="magenta")
101+
if license_bool := not "LICENSE" in hide_parameters:
102+
table.add_column("License(s)", style="magenta")
98103
licenseCompat = (
99104
"[red]✖[/]",
100105
"[green]✔[/]",
101106
)
102-
_ = [table.add_row(licenseCompat[x.licenseCompat], x.name, x.license) for x in packages]
107+
_ = [
108+
table.add_row(
109+
*(
110+
([licenseCompat[x.licenseCompat]] if licensecompat_bool else []) +
111+
([x.name] if name_bool else []) +
112+
([x.license] if license_bool else [])
113+
)
114+
)
115+
for x in packages
116+
]
103117
console.print(table)
104118
return string.getvalue()
105119

106120

107-
def plainText(myLice: License, packages: list[PackageInfo]) -> str:
121+
def plainText(myLice: License, packages: list[PackageInfo], hide_parameters: list[str] = []) -> str:
108122
"""Format to ansi.
109123
110124
Args:
111125
----
112126
myLice (License): project license
113127
packages (list[PackageInfo]): list of PackageCompats to format.
128+
hide_parameters (list[str]): list of parameters to ignore in the output.
114129
115130
Returns:
116131
-------
117132
str: string to send to specified output in plain text format
118133
119134
"""
120-
return stripAnsi(ansi(myLice, packages))
135+
return stripAnsi(ansi(myLice, packages, hide_parameters))
121136

122137

123-
def markdown(myLice: License, packages: list[PackageInfo]) -> str:
138+
def markdown(myLice: License, packages: list[PackageInfo], hide_parameters: list[str] = []) -> str:
124139
"""Format to markdown.
125140
126141
Args:
127142
----
128143
myLice (License): project license
129144
packages (list[PackageInfo]): list of PackageCompats to format.
145+
hide_parameters (list[str]): list of parameters to ignore in the output.
130146
131147
Returns:
132148
-------
@@ -148,27 +164,36 @@ def markdown(myLice: License, packages: list[PackageInfo]) -> str:
148164
strBuf.append(f"|{'✔' if pkg.licenseCompat else '✖'}|{pkg.name}|")
149165

150166
# Details
167+
params_use_in_markdown = {
168+
"homePage": "HomePage",
169+
"author": "Author",
170+
"license": "License",
171+
"licenseCompat": "Compatible",
172+
"size": "Size",
173+
}
151174
for pkg in packages:
175+
pkg_dict = pkg.get_filtered_dict(hide_parameters)
176+
pkg_dict_ordered_dict = OrderedDict((param, pkg_dict[param]) for param in params_use_in_markdown.keys() if param in pkg_dict)
152177
strBuf.extend(
153178
[
154-
f"\n### {pkg.namever}",
155-
f"\n- HomePage: {pkg.homePage}",
156-
f"- Author: {pkg.author}",
157-
f"- License: {pkg.license}",
158-
f"- Compatible: {pkg.licenseCompat}",
159-
f"- Size: {pkg.size}",
179+
f"\n### {pkg.namever}\n",
180+
*(
181+
f"- {params_use_in_markdown[k]}: {v}"
182+
for k, v in pkg_dict_ordered_dict.items()
183+
),
160184
]
161185
)
162186
return "\n".join(strBuf) + "\n"
163187

164188

165-
def raw(myLice: License, packages: list[PackageInfo]) -> str:
189+
def raw(myLice: License, packages: list[PackageInfo], hide_parameters: list[str] = []) -> str:
166190
"""Format to json.
167191
168192
Args:
169193
----
170194
myLice (License): project license
171195
packages (list[PackageInfo]): list of PackageCompats to format.
196+
hide_parameters (list[str]): list of parameters to ignore in the output.
172197
173198
Returns:
174199
-------
@@ -179,19 +204,23 @@ def raw(myLice: License, packages: list[PackageInfo]) -> str:
179204
{
180205
"info": INFO,
181206
"project_license": printLicense(myLice),
182-
"packages": [x.__dict__ for x in packages],
207+
"packages": [
208+
x.get_filtered_dict(hide_parameters)
209+
for x in packages
210+
],
183211
},
184212
indent="\t",
185213
)
186214

187215

188-
def rawCsv(myLice: License, packages: list[PackageInfo]) -> str:
216+
def rawCsv(myLice: License, packages: list[PackageInfo], hide_parameters: list[str] = []) -> str:
189217
"""Format to csv.
190218
191219
Args:
192220
----
193221
myLice (License): project license
194222
packages (list[PackageInfo]): list of PackageCompats to format.
223+
hide_parameters (list[str]): list of parameters to ignore in the output.
195224
196225
Returns:
197226
-------
@@ -202,7 +231,10 @@ def rawCsv(myLice: License, packages: list[PackageInfo]) -> str:
202231
string = StringIO()
203232
writer = csv.DictWriter(string, fieldnames=list(packages[0].__dict__), lineterminator="\n")
204233
writer.writeheader()
205-
writer.writerows([x.__dict__ for x in packages])
234+
writer.writerows([
235+
x.get_filtered_dict(hide_parameters)
236+
for x in packages
237+
])
206238
return string.getvalue()
207239

208240

licensecheck/types.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,18 @@ def __post_init__(self) -> None:
5050
"""Set the namever once the object is initialised."""
5151
self.namever = f"{self.name}-{self.version}"
5252

53+
def get_filtered_dict(self, hide_output_parameters: list[str]) -> dict:
54+
"""Return a filtered dictionary of the object.
55+
56+
:param list[str] hide_output_parameters: list of parameters to ignore
57+
:return dict: filtered dictionary
58+
"""
59+
return {
60+
k: v
61+
for k, v in self.__dict__.items()
62+
if k.upper() not in hide_output_parameters
63+
}
64+
5365

5466
class License(Enum):
5567
"""License Enum to hold a set of potential licenses."""

tests/conftest.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import logging
2+
3+
import pytest # pyright: ignore [reportMissingImports]
4+
from loguru import logger
5+
from _pytest.logging import caplog as _caplog
6+
7+
8+
@pytest.fixture()
9+
def caplog(_caplog):
10+
"""Wrapper over caplog fixture to fix loguru logs.
11+
12+
Yields
13+
------
14+
_caplog: Pytest fixture
15+
"""
16+
17+
class PropogateHandler(logging.Handler):
18+
def emit(self, record):
19+
logging.getLogger(record.name).handle(record)
20+
21+
logger.add(PropogateHandler(), format="{message}")
22+
handler_id = logger.add(PropogateHandler(), format="{message}")
23+
yield _caplog
24+
logger.remove(handler_id)

tests/data/advanced.ansi

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
 
22
 Info 
3-
┌─────────────────┬──────────────┐
4-
 Item   Value  
5-
├─────────────────┼──────────────┤
3+
┏━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓
4+
 Item   Value  
5+
┡━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━┩
66
│ program  │ licensecheck │
77
│ version  │ 2024  │
88
│ license  │ MIT LICENSE  │
@@ -11,16 +11,16 @@
1111
 
1212
 List Of 
1313
 Errors 
14-
┌──────────┐
15-
 Package  
16-
├──────────┤
14+
┏━━━━━━━━━━┓
15+
 Package  
16+
┡━━━━━━━━━━┩
1717
│ example1 │
1818
└──────────┘
1919
 
2020
 List Of Packages 
21-
┌────────────┬──────────┬────────────┐
22-
 Compatible  Package   License(s) 
23-
├────────────┼──────────┼────────────┤
21+
┏━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━┓
22+
 Compatible  Package   License(s) 
23+
┡━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━┩
2424
│ ✔  │ example0 │ MIT  │
2525
│ ✖  │ example1 │ GPL3  │
2626
└────────────┴──────────┴────────────┘

tests/data/advanced.txt

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11

22
Info
3-
┌─────────────────┬──────────────┐
4-
Item Value
5-
├─────────────────┼──────────────┤
3+
┏━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓
4+
Item Value
5+
┡━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━┩
66
│ program │ licensecheck │
77
│ version │ 2024 │
88
│ license │ MIT LICENSE │
@@ -11,16 +11,16 @@
1111

1212
List Of
1313
Errors
14-
┌──────────┐
15-
Package
16-
├──────────┤
14+
┏━━━━━━━━━━┓
15+
Package
16+
┡━━━━━━━━━━┩
1717
│ example1 │
1818
└──────────┘
1919

2020
List Of Packages
21-
┌────────────┬──────────┬────────────┐
22-
Compatible Package License(s)
23-
├────────────┼──────────┼────────────┤
21+
┏━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━┓
22+
Compatible Package License(s)
23+
┡━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━┩
2424
│ ✔ │ example0 │ MIT │
2525
│ ✖ │ example1 │ GPL3 │
2626
└────────────┴──────────┴────────────┘
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
{
2+
"info": {
3+
"program": "licensecheck",
4+
"version": "2024",
5+
"license": "MIT LICENSE"
6+
},
7+
"project_license": "MIT LICENSE",
8+
"packages": [
9+
{
10+
"name": "example0",
11+
"version": "1.0.0",
12+
"size": 10,
13+
"license": "MIT",
14+
"licenseCompat": true,
15+
"errorCode": 0,
16+
"namever": "example0-1.0.0"
17+
},
18+
{
19+
"name": "example1",
20+
"version": "UNKNOWN",
21+
"size": 10,
22+
"license": "GPL3",
23+
"licenseCompat": false,
24+
"errorCode": 1,
25+
"namever": "example1-UNKNOWN"
26+
}
27+
]
28+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
## Info
2+
3+
- **program**: licensecheck
4+
- **version**: 2024
5+
- **license**: MIT LICENSE
6+
7+
## Project License
8+
9+
MIT LICENSE
10+
11+
## Packages
12+
13+
Find a list of packages below
14+
15+
|Compatible|Package|
16+
|:--|:--|
17+
||example0|
18+
||example1|
19+
20+
### example0-1.0.0
21+
22+
- HomePage: https://example.com
23+
- Author: example_author
24+
- License: MIT
25+
- Compatible: True
26+
27+
### example1-UNKNOWN
28+
29+
- HomePage: https://example.com
30+
- Author: example_author
31+
- License: GPL3
32+
- Compatible: False

0 commit comments

Comments
 (0)