findbib 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- findbib/__init__.py +6 -0
- findbib/__main__.py +5 -0
- findbib/bibparse.py +192 -0
- findbib/cli.py +227 -0
- findbib/config.py +75 -0
- findbib/data/abbreviation-short.bib +1641 -0
- findbib/data/abbreviation.bib +1643 -0
- findbib/doi/__init__.py +44 -0
- findbib/doi/authors.py +275 -0
- findbib/doi/browser.py +39 -0
- findbib/doi/cli.py +46 -0
- findbib/doi/conferences/__init__.py +1 -0
- findbib/doi/conferences/base.py +130 -0
- findbib/doi/conferences/iclr.py +54 -0
- findbib/doi/conferences/metadata.py +68 -0
- findbib/doi/conferences/neurips.py +256 -0
- findbib/doi/conferences/openreview.py +238 -0
- findbib/doi/conferences/pmlr.py +121 -0
- findbib/doi/constants.py +137 -0
- findbib/doi/crossref.py +93 -0
- findbib/doi/formatting.py +56 -0
- findbib/doi/geo.py +87 -0
- findbib/doi/keys.py +83 -0
- findbib/doi/log.py +51 -0
- findbib/doi/ltwa.py +113 -0
- findbib/doi/matching.py +100 -0
- findbib/doi/net.py +64 -0
- findbib/doi/pdf.py +152 -0
- findbib/doi/pipeline.py +305 -0
- findbib/doi/preprints.py +107 -0
- findbib/doi/publishers/__init__.py +1 -0
- findbib/doi/publishers/acm.py +52 -0
- findbib/doi/publishers/cvpr.py +35 -0
- findbib/doi/publishers/elsevier.py +28 -0
- findbib/doi/publishers/ieee.py +79 -0
- findbib/doi/publishers/iop.py +25 -0
- findbib/doi/publishers/mdpi.py +58 -0
- findbib/doi/publishers/spie.py +33 -0
- findbib/doi/publishers/springer.py +300 -0
- findbib/doi/record.py +333 -0
- findbib/doi/resolve.py +116 -0
- findbib/doi/settings.py +86 -0
- findbib/doi/strings.py +26 -0
- findbib/index.py +233 -0
- findbib/latex.py +28 -0
- findbib/lookup.py +95 -0
- findbib/search.py +374 -0
- findbib/server.py +225 -0
- findbib/static/index.html +273 -0
- findbib/update.py +328 -0
- findbib-0.1.0.dist-info/METADATA +338 -0
- findbib-0.1.0.dist-info/RECORD +56 -0
- findbib-0.1.0.dist-info/WHEEL +5 -0
- findbib-0.1.0.dist-info/entry_points.txt +2 -0
- findbib-0.1.0.dist-info/licenses/LICENSE +661 -0
- findbib-0.1.0.dist-info/top_level.txt +1 -0
findbib/__init__.py
ADDED
findbib/__main__.py
ADDED
findbib/bibparse.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Lossless BibTeX parser (from the findbib prototype, unchanged).
|
|
2
|
+
|
|
3
|
+
Splits a .bib file into an ordered list of blocks:
|
|
4
|
+
- ('text', raw) : anything outside an @-command (comments, blank lines)
|
|
5
|
+
- ('entry', raw, parsed) : an @type{key, field = value, ...}
|
|
6
|
+
- ('string', raw, parsed) : an @string{name = value}
|
|
7
|
+
Concatenating every block's raw text gives back the file byte for byte.
|
|
8
|
+
|
|
9
|
+
A value is parsed into parts, each part being one of
|
|
10
|
+
('braced', inner) ('quoted', inner) ('number', text) ('macro', name)
|
|
11
|
+
joined by '#'.
|
|
12
|
+
"""
|
|
13
|
+
import re
|
|
14
|
+
|
|
15
|
+
NAME_RE = re.compile(r'[^\s"#%\'(),={}]+')
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ParseError(Exception):
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _skip_ws(s, i):
|
|
23
|
+
n = len(s)
|
|
24
|
+
while i < n and s[i] in ' \t\r\n':
|
|
25
|
+
i += 1
|
|
26
|
+
return i
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _read_braced(s, i):
|
|
30
|
+
"""s[i] == '{'; return (inner, index after closing brace)."""
|
|
31
|
+
assert s[i] == '{'
|
|
32
|
+
depth = 0
|
|
33
|
+
j = i
|
|
34
|
+
n = len(s)
|
|
35
|
+
while j < n:
|
|
36
|
+
c = s[j]
|
|
37
|
+
if c == '\\' and j + 1 < n: # \{ and \} do not count
|
|
38
|
+
j += 2
|
|
39
|
+
continue
|
|
40
|
+
if c == '{':
|
|
41
|
+
depth += 1
|
|
42
|
+
elif c == '}':
|
|
43
|
+
depth -= 1
|
|
44
|
+
if depth == 0:
|
|
45
|
+
return s[i + 1:j], j + 1
|
|
46
|
+
j += 1
|
|
47
|
+
raise ParseError(f'unbalanced braces starting at {i}')
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _read_quoted(s, i):
|
|
51
|
+
assert s[i] == '"'
|
|
52
|
+
depth = 0
|
|
53
|
+
j = i + 1
|
|
54
|
+
n = len(s)
|
|
55
|
+
while j < n:
|
|
56
|
+
c = s[j]
|
|
57
|
+
if c == '\\' and j + 1 < n:
|
|
58
|
+
j += 2
|
|
59
|
+
continue
|
|
60
|
+
if c == '{':
|
|
61
|
+
depth += 1
|
|
62
|
+
elif c == '}':
|
|
63
|
+
depth -= 1
|
|
64
|
+
elif c == '"' and depth == 0:
|
|
65
|
+
return s[i + 1:j], j + 1
|
|
66
|
+
j += 1
|
|
67
|
+
raise ParseError(f'unterminated quote starting at {i}')
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _read_value(s, i):
|
|
71
|
+
"""Return (parts, index after value)."""
|
|
72
|
+
parts = []
|
|
73
|
+
while True:
|
|
74
|
+
i = _skip_ws(s, i)
|
|
75
|
+
c = s[i]
|
|
76
|
+
if c == '{':
|
|
77
|
+
inner, i = _read_braced(s, i)
|
|
78
|
+
parts.append(('braced', inner))
|
|
79
|
+
elif c == '"':
|
|
80
|
+
inner, i = _read_quoted(s, i)
|
|
81
|
+
parts.append(('quoted', inner))
|
|
82
|
+
else:
|
|
83
|
+
m = NAME_RE.match(s, i)
|
|
84
|
+
if not m:
|
|
85
|
+
raise ParseError(f'bad value at {i}: {s[i:i+40]!r}')
|
|
86
|
+
tok = m.group(0)
|
|
87
|
+
parts.append(('number' if tok.isdigit() else 'macro', tok))
|
|
88
|
+
i = m.end()
|
|
89
|
+
j = _skip_ws(s, i)
|
|
90
|
+
if j < len(s) and s[j] == '#':
|
|
91
|
+
i = j + 1
|
|
92
|
+
continue
|
|
93
|
+
return parts, i
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _parse_body(s, i, close):
|
|
97
|
+
"""Parse 'key, f = v, ...' (entry) up to the closing delimiter."""
|
|
98
|
+
i = _skip_ws(s, i)
|
|
99
|
+
m = re.compile(r'[^,\s}]+').match(s, i)
|
|
100
|
+
if not m:
|
|
101
|
+
raise ParseError(f'missing key at {i}')
|
|
102
|
+
key = m.group(0)
|
|
103
|
+
i = m.end()
|
|
104
|
+
fields = []
|
|
105
|
+
trailing_comma = False
|
|
106
|
+
while True:
|
|
107
|
+
i = _skip_ws(s, i)
|
|
108
|
+
if s[i] == close:
|
|
109
|
+
return key, fields, trailing_comma, i + 1
|
|
110
|
+
if s[i] != ',':
|
|
111
|
+
raise ParseError(f'expected , or {close} at {i}: {s[i:i+40]!r} (entry {key})')
|
|
112
|
+
i = _skip_ws(s, i + 1)
|
|
113
|
+
if s[i] == close:
|
|
114
|
+
trailing_comma = True
|
|
115
|
+
return key, fields, trailing_comma, i + 1
|
|
116
|
+
m = NAME_RE.match(s, i)
|
|
117
|
+
if not m:
|
|
118
|
+
raise ParseError(f'bad field name at {i}: {s[i:i+40]!r} (entry {key})')
|
|
119
|
+
fname = m.group(0)
|
|
120
|
+
i = _skip_ws(s, m.end())
|
|
121
|
+
if s[i] != '=':
|
|
122
|
+
raise ParseError(f'expected = at {i} (entry {key}, field {fname})')
|
|
123
|
+
parts, i = _read_value(s, i + 1)
|
|
124
|
+
fields.append((fname, parts))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def parse(text):
|
|
128
|
+
blocks = []
|
|
129
|
+
i = 0
|
|
130
|
+
n = len(text)
|
|
131
|
+
last = 0
|
|
132
|
+
at_re = re.compile(r'@[ \t]*([A-Za-z]+)[ \t]*([{(])')
|
|
133
|
+
while True:
|
|
134
|
+
m = at_re.search(text, i)
|
|
135
|
+
if not m:
|
|
136
|
+
break
|
|
137
|
+
# in BibTeX, '@' starts a command anywhere outside entries
|
|
138
|
+
start = m.start()
|
|
139
|
+
kind = m.group(1)
|
|
140
|
+
opener = m.group(2)
|
|
141
|
+
close = '}' if opener == '{' else ')'
|
|
142
|
+
j = m.end()
|
|
143
|
+
lk = kind.lower()
|
|
144
|
+
if lk == 'comment':
|
|
145
|
+
# @comment{...}: keep verbatim as text
|
|
146
|
+
if opener == '{':
|
|
147
|
+
_, j = _read_braced(text, j - 1)
|
|
148
|
+
i = j
|
|
149
|
+
continue
|
|
150
|
+
if start > last:
|
|
151
|
+
blocks.append(('text', text[last:start]))
|
|
152
|
+
# BibTeX does NOT treat '%' as a comment: '% @STRING{...}' is active.
|
|
153
|
+
line_start = text.rfind('\n', 0, start) + 1
|
|
154
|
+
percent_line = text[line_start:start].lstrip().startswith('%')
|
|
155
|
+
if lk == 'string':
|
|
156
|
+
j = _skip_ws(text, j)
|
|
157
|
+
mm = NAME_RE.match(text, j)
|
|
158
|
+
name = mm.group(0)
|
|
159
|
+
j = _skip_ws(text, mm.end())
|
|
160
|
+
assert text[j] == '=', (start, text[start:start+80])
|
|
161
|
+
parts, j = _read_value(text, j + 1)
|
|
162
|
+
j = _skip_ws(text, j)
|
|
163
|
+
assert text[j] == close
|
|
164
|
+
j += 1
|
|
165
|
+
blocks.append(('string', text[start:j], {'kind': kind, 'name': name, 'parts': parts, 'percent_line': percent_line}))
|
|
166
|
+
elif lk == 'preamble':
|
|
167
|
+
parts, j = _read_value(text, j)
|
|
168
|
+
j = _skip_ws(text, j)
|
|
169
|
+
assert text[j] == close
|
|
170
|
+
j += 1
|
|
171
|
+
blocks.append(('preamble', text[start:j], {'kind': kind, 'parts': parts}))
|
|
172
|
+
else:
|
|
173
|
+
key, fields, tc, j = _parse_body(text, j, close)
|
|
174
|
+
blocks.append(('entry', text[start:j], {
|
|
175
|
+
'type': kind, 'key': key, 'fields': fields, 'trailing_comma': tc, 'percent_line': percent_line}))
|
|
176
|
+
last = i = j
|
|
177
|
+
if last < n:
|
|
178
|
+
blocks.append(('text', text[last:]))
|
|
179
|
+
assert ''.join(b[1] for b in blocks) == text
|
|
180
|
+
return blocks
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def render_value(parts):
|
|
184
|
+
out = []
|
|
185
|
+
for k, v in parts:
|
|
186
|
+
if k == 'braced':
|
|
187
|
+
out.append('{' + v + '}')
|
|
188
|
+
elif k == 'quoted':
|
|
189
|
+
out.append('"' + v + '"')
|
|
190
|
+
else:
|
|
191
|
+
out.append(v)
|
|
192
|
+
return ' # '.join(out)
|
findbib/cli.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""Command line.
|
|
2
|
+
|
|
3
|
+
findbib [--data-dir DIR] start the local page and open the browser
|
|
4
|
+
findbib TEXT... print the entry in the console (same as get)
|
|
5
|
+
findbib get TEXT... a key, words, DOI, arXiv id or URL: local, else online
|
|
6
|
+
findbib search WORDS... list matching entries (key, year, title)
|
|
7
|
+
findbib doi DOI|URL... the former doi2bib (always online)
|
|
8
|
+
findbib serve [--port N] [--no-browser]
|
|
9
|
+
findbib update [--url U] [--check]
|
|
10
|
+
findbib index [--rebuild] [--export OUT.sqlite FILE.bib...]
|
|
11
|
+
findbib info folders, number of entries, parse problems
|
|
12
|
+
|
|
13
|
+
The first word that is not an option decides: a command name runs that command,
|
|
14
|
+
anything else is a text to look up (``findbib get index`` looks up "index").
|
|
15
|
+
|
|
16
|
+
Options accepted before or after the command: ``--data-dir DIR`` selects another
|
|
17
|
+
data folder, ``--set-default`` stores it in the configuration, ``-v``, ``-vv``
|
|
18
|
+
and ``-vvv`` explain on stderr what is done (decisions, processing, data).
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import argparse
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import shlex
|
|
26
|
+
import sys
|
|
27
|
+
from typing import List, Optional
|
|
28
|
+
|
|
29
|
+
from . import __version__
|
|
30
|
+
from .config import config_path, load_config, save_config
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
COMMANDS = ("serve", "search", "get", "doi", "update", "index", "info")
|
|
34
|
+
#: Options followed by a value, which must not be mistaken for the text.
|
|
35
|
+
_WITH_VALUE = ("--data-dir", "--mode", "--port", "--url", "--export", "-n")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _with_command(argv: List[str]) -> List[str]:
|
|
39
|
+
"""Add the command that was left out: ``get`` if there is a text to look
|
|
40
|
+
up, otherwise ``serve``."""
|
|
41
|
+
args = iter(argv)
|
|
42
|
+
for a in args:
|
|
43
|
+
if a == "--": # everything after it is text
|
|
44
|
+
return ["get", *argv]
|
|
45
|
+
if a in ("-h", "--help", "--version"):
|
|
46
|
+
return argv
|
|
47
|
+
if a in _WITH_VALUE:
|
|
48
|
+
next(args, None)
|
|
49
|
+
elif not a.startswith("-") or a == "-":
|
|
50
|
+
return argv if a in COMMANDS else ["get", *argv]
|
|
51
|
+
return ["serve", *argv]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _common(where: str) -> argparse.ArgumentParser:
|
|
55
|
+
"""Options accepted before and after the command. ``-v`` is counted
|
|
56
|
+
separately in both places, because argparse lets the second overwrite the
|
|
57
|
+
first."""
|
|
58
|
+
p = argparse.ArgumentParser(add_help=False, allow_abbrev=False)
|
|
59
|
+
p.add_argument("--data-dir", default=argparse.SUPPRESS,
|
|
60
|
+
help="folder with your .bib files (default: see 'findbib info')")
|
|
61
|
+
p.add_argument("--set-default", action="store_true", default=argparse.SUPPRESS,
|
|
62
|
+
help="remember --data-dir for next time")
|
|
63
|
+
p.add_argument("-v", "--verbose", "--verbosity", dest="verbose_" + where, action="count", default=0,
|
|
64
|
+
help="explain on stderr: -v decisions, -vv processing, -vvv data")
|
|
65
|
+
return p
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _parser() -> argparse.ArgumentParser:
|
|
69
|
+
common = _common("after")
|
|
70
|
+
p = argparse.ArgumentParser(prog="findbib", parents=[_common("before")], allow_abbrev=False,
|
|
71
|
+
usage="findbib [options] [TEXT... | COMMAND ...]",
|
|
72
|
+
description="Find a BibTeX entry in your own .bib files, "
|
|
73
|
+
"or fetch it from its DOI. With a TEXT, print the "
|
|
74
|
+
"entry; with nothing, open the local page.")
|
|
75
|
+
p.add_argument("--version", action="version", version="findbib " + __version__)
|
|
76
|
+
sub = p.add_subparsers(dest="cmd", metavar="COMMAND", prog="findbib")
|
|
77
|
+
|
|
78
|
+
s = sub.add_parser("serve", parents=[common], allow_abbrev=False, help="start the local web page (default)")
|
|
79
|
+
s.add_argument("--port", type=int, help="port on 127.0.0.1 (default 8517, 0 = any free port)")
|
|
80
|
+
s.add_argument("--no-browser", action="store_true", help="do not open the browser")
|
|
81
|
+
|
|
82
|
+
s = sub.add_parser("search", parents=[common], allow_abbrev=False, help="search your .bib files")
|
|
83
|
+
s.add_argument("words", nargs="+")
|
|
84
|
+
s.add_argument("-n", type=int, default=8, help="number of results (default 8)")
|
|
85
|
+
s.add_argument("--json", action="store_true")
|
|
86
|
+
|
|
87
|
+
s = sub.add_parser("get", parents=[common], allow_abbrev=False, help="print one entry (local first, then online)")
|
|
88
|
+
s.add_argument("text", nargs="+", help="key, words, DOI, arXiv id or URL")
|
|
89
|
+
s.add_argument("--mode", choices=("raw", "long", "short"), default="raw",
|
|
90
|
+
help="raw: @string macros kept; long/short: expanded")
|
|
91
|
+
s.add_argument("--offline", action="store_true", help="never go online")
|
|
92
|
+
s.add_argument("--no-save", action="store_true", help="do not save fetched entries")
|
|
93
|
+
|
|
94
|
+
from .doi import cli as doi_cli
|
|
95
|
+
s = sub.add_parser("doi", parents=[common], allow_abbrev=False, help="fetch from a DOI or URL (the former doi2bib)")
|
|
96
|
+
doi_cli.add_arguments(s)
|
|
97
|
+
|
|
98
|
+
s = sub.add_parser("update", parents=[common], allow_abbrev=False, help="download shared bibliographies")
|
|
99
|
+
s.add_argument("--url", action="append", help="manifest URL (default: from the configuration)")
|
|
100
|
+
s.add_argument("--check", action="store_true", help="only list what would be downloaded")
|
|
101
|
+
|
|
102
|
+
s = sub.add_parser("index", parents=[common], allow_abbrev=False, help="re-read the .bib files or export an index")
|
|
103
|
+
s.add_argument("--rebuild", action="store_true", help="forget the index and re-read every file")
|
|
104
|
+
s.add_argument("--export", metavar="OUT.sqlite", help="write a standalone index of FILES")
|
|
105
|
+
s.add_argument("files", nargs="*", help=".bib files for --export")
|
|
106
|
+
|
|
107
|
+
sub.add_parser("info", parents=[common], allow_abbrev=False, help="show folders and library statistics")
|
|
108
|
+
return p
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
112
|
+
argv = _with_command(list(sys.argv[1:] if argv is None else argv))
|
|
113
|
+
args = _parser().parse_args(argv)
|
|
114
|
+
from .doi.log import debug
|
|
115
|
+
from .doi.settings import settings
|
|
116
|
+
settings.verbosity = args.verbose_before + getattr(args, "verbose_after", 0)
|
|
117
|
+
cfg = load_config()
|
|
118
|
+
args.data_dir = getattr(args, "data_dir", None)
|
|
119
|
+
data_dir = cfg.resolved_data_dir(args.data_dir)
|
|
120
|
+
if getattr(args, "set_default", False) and args.data_dir:
|
|
121
|
+
cfg.data_dir = data_dir
|
|
122
|
+
save_config(cfg)
|
|
123
|
+
cmd = args.cmd
|
|
124
|
+
|
|
125
|
+
if cmd == "doi":
|
|
126
|
+
from .doi import cli as doi_cli
|
|
127
|
+
return doi_cli.run(args)
|
|
128
|
+
|
|
129
|
+
if cmd == "update":
|
|
130
|
+
from .update import update
|
|
131
|
+
status = 0
|
|
132
|
+
for url in args.url or cfg.update_urls:
|
|
133
|
+
try:
|
|
134
|
+
r = update(data_dir, url, check_only=args.check)
|
|
135
|
+
except Exception as exc:
|
|
136
|
+
print(f"{url}: {exc}", file=sys.stderr)
|
|
137
|
+
status = 1
|
|
138
|
+
continue
|
|
139
|
+
verb = "to download" if args.check else "downloaded"
|
|
140
|
+
print(f"{url} (release {r.release or '?'}) -> {r.target}")
|
|
141
|
+
print(f" {verb}: {', '.join(r.downloaded) or 'nothing'}; unchanged: {len(r.unchanged)}"
|
|
142
|
+
+ (f"; removed: {', '.join(r.removed)}" if r.removed else ""))
|
|
143
|
+
for e in r.errors:
|
|
144
|
+
print(" error: " + e, file=sys.stderr)
|
|
145
|
+
status = 1
|
|
146
|
+
return status
|
|
147
|
+
|
|
148
|
+
if cmd == "index" and args.export:
|
|
149
|
+
from .index import export_index
|
|
150
|
+
if not args.files:
|
|
151
|
+
print("--export needs .bib files", file=sys.stderr)
|
|
152
|
+
return 2
|
|
153
|
+
r = export_index(args.files, args.export)
|
|
154
|
+
print(f"{args.export}: {len(r.added)} file(s)")
|
|
155
|
+
for f, e in r.errors.items():
|
|
156
|
+
print(f" {f}: {e}", file=sys.stderr)
|
|
157
|
+
return 0
|
|
158
|
+
|
|
159
|
+
from .search import Library
|
|
160
|
+
from . import doi
|
|
161
|
+
from .server import _abbreviation_in
|
|
162
|
+
doi.settings.abbreviation_path = _abbreviation_in(data_dir)
|
|
163
|
+
|
|
164
|
+
if cmd == "serve":
|
|
165
|
+
from .server import serve
|
|
166
|
+
port = getattr(args, "port", None)
|
|
167
|
+
serve(cfg, data_dir, port=cfg.port if port is None else port,
|
|
168
|
+
open_browser=not getattr(args, "no_browser", False))
|
|
169
|
+
return 0
|
|
170
|
+
|
|
171
|
+
debug(1, "data folder: " + data_dir)
|
|
172
|
+
lib = Library(data_dir)
|
|
173
|
+
if cmd == "index" and args.rebuild:
|
|
174
|
+
try:
|
|
175
|
+
os.remove(lib.index_file)
|
|
176
|
+
except FileNotFoundError:
|
|
177
|
+
pass
|
|
178
|
+
lib.refresh(force=True)
|
|
179
|
+
|
|
180
|
+
debug(1, f"{len(lib.entries)} entries in {len(lib.files)} file(s)")
|
|
181
|
+
|
|
182
|
+
if cmd == "search":
|
|
183
|
+
hits = lib.search(" ".join(args.words), limit=args.n)
|
|
184
|
+
if args.json:
|
|
185
|
+
print(json.dumps([e.summary() for e in hits], ensure_ascii=False, indent=1))
|
|
186
|
+
for e in hits if not args.json else []:
|
|
187
|
+
print(f"{e.key}\t{e.year}\t{e.title}")
|
|
188
|
+
return 0 if hits else 1
|
|
189
|
+
|
|
190
|
+
if cmd == "get":
|
|
191
|
+
from .lookup import NotFound, lookup
|
|
192
|
+
try:
|
|
193
|
+
r = lookup(lib, " ".join(args.text), args.mode,
|
|
194
|
+
save=cfg.save_fetched and not args.no_save, online=not args.offline)
|
|
195
|
+
except NotFound as exc:
|
|
196
|
+
print(exc, file=sys.stderr)
|
|
197
|
+
return 1
|
|
198
|
+
except Exception as exc:
|
|
199
|
+
print(exc, file=sys.stderr)
|
|
200
|
+
return 1
|
|
201
|
+
print(r.bibtex)
|
|
202
|
+
for w in r.warnings:
|
|
203
|
+
print(w, file=sys.stderr)
|
|
204
|
+
if r.others:
|
|
205
|
+
print(f"findbib: {r.others} other {'entry matches' if r.others == 1 else 'entries match'}; "
|
|
206
|
+
"list with: findbib search " + shlex.join(args.text), file=sys.stderr)
|
|
207
|
+
return 0
|
|
208
|
+
|
|
209
|
+
# info / index
|
|
210
|
+
s = lib.stats()
|
|
211
|
+
print(f"findbib {__version__}")
|
|
212
|
+
print(f"config file : {config_path()}")
|
|
213
|
+
print(f"data folder : {s['data_dir']}")
|
|
214
|
+
print(f"index : {s['index']}")
|
|
215
|
+
print(f"entries : {s['entries']} in {len(s['files'])} file(s); {s['macros']} @string macros")
|
|
216
|
+
for f in s["files"]:
|
|
217
|
+
print(f" {f}")
|
|
218
|
+
for f, e in s["errors"].items():
|
|
219
|
+
print(f"parse problems in {f}:\n " + e.replace("\n", "\n "))
|
|
220
|
+
if s["n_duplicates"]:
|
|
221
|
+
print(f"{s['n_duplicates']} duplicate key(s) (first kept), e.g. " + "; ".join(s["duplicates"][:5]))
|
|
222
|
+
print(f"abbreviation.bib used for DOIs: {doi.settings.abbreviation_file()}")
|
|
223
|
+
return 0
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
if __name__ == "__main__":
|
|
227
|
+
sys.exit(main())
|
findbib/config.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""User settings and folders.
|
|
2
|
+
|
|
3
|
+
* data folder : the .bib files that findbib searches (each user chooses it);
|
|
4
|
+
default ``platformdirs.user_data_dir("findbib")``, i.e.
|
|
5
|
+
~/Library/Application Support/findbib (macOS),
|
|
6
|
+
~/.local/share/findbib (Linux), %LOCALAPPDATA%\\findbib (Windows).
|
|
7
|
+
* config file : ``user_config_dir("findbib")/config.json``.
|
|
8
|
+
* index (cache) : ``user_cache_dir("findbib")/index-<hash>.sqlite``, one per data
|
|
9
|
+
folder; it can always be deleted and is rebuilt automatically.
|
|
10
|
+
|
|
11
|
+
Precedence for the data folder: ``--data-dir`` > ``$FINDBIB_DATA_DIR`` >
|
|
12
|
+
config.json > default.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
from dataclasses import asdict, dataclass, field
|
|
20
|
+
from typing import List, Optional
|
|
21
|
+
|
|
22
|
+
from platformdirs import user_cache_dir, user_config_dir, user_data_dir
|
|
23
|
+
|
|
24
|
+
APP = "findbib"
|
|
25
|
+
DEFAULT_UPDATE_URL = "https://find.uliege.be/bib/manifest.json"
|
|
26
|
+
FETCHED_FILE = "findbib-fetched.bib"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def config_path() -> str:
|
|
30
|
+
return os.path.join(user_config_dir(APP, appauthor=False), "config.json")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def default_data_dir() -> str:
|
|
34
|
+
return user_data_dir(APP, appauthor=False)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class Config:
|
|
39
|
+
data_dir: Optional[str] = None
|
|
40
|
+
#: manifests read by ``findbib update`` (see docs/manifest.md)
|
|
41
|
+
update_urls: List[str] = field(default_factory=lambda: [DEFAULT_UPDATE_URL])
|
|
42
|
+
#: append entries fetched online to <data_dir>/findbib-fetched.bib,
|
|
43
|
+
#: which makes them searchable and works as a cache
|
|
44
|
+
save_fetched: bool = True
|
|
45
|
+
#: "raw" (macros kept), "long" or "short"
|
|
46
|
+
mode: str = "raw"
|
|
47
|
+
port: int = 8517 # 0: pick a free port
|
|
48
|
+
|
|
49
|
+
def resolved_data_dir(self, override: Optional[str] = None) -> str:
|
|
50
|
+
d = override or os.environ.get("FINDBIB_DATA_DIR") or self.data_dir or default_data_dir()
|
|
51
|
+
return os.path.abspath(os.path.expanduser(d))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def load_config() -> Config:
|
|
55
|
+
try:
|
|
56
|
+
with open(config_path(), encoding="utf-8") as f:
|
|
57
|
+
raw = json.load(f)
|
|
58
|
+
except (OSError, ValueError):
|
|
59
|
+
return Config()
|
|
60
|
+
known = {k: v for k, v in raw.items() if k in Config.__dataclass_fields__}
|
|
61
|
+
return Config(**known)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def save_config(cfg: Config) -> None:
|
|
65
|
+
path = config_path()
|
|
66
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
67
|
+
tmp = path + ".tmp"
|
|
68
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
69
|
+
json.dump(asdict(cfg), f, indent=2)
|
|
70
|
+
os.replace(tmp, path)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def index_path(data_dir: str) -> str:
|
|
74
|
+
h = hashlib.sha256(os.path.abspath(data_dir).encode("utf-8")).hexdigest()[:16]
|
|
75
|
+
return os.path.join(user_cache_dir(APP, appauthor=False), f"index-{h}.sqlite")
|