Skip to content

Commit

Permalink
GbibClean adding option --rename-field (#79)
Browse files Browse the repository at this point in the history
  • Loading branch information
tdegeus authored Oct 25, 2023
1 parent a14cd8c commit c043082
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
16 changes: 16 additions & 0 deletions GooseBib/bibtex.py
Original file line number Diff line number Diff line change
Expand Up @@ -1035,6 +1035,14 @@ def _split_lines(self, text, width):
),
)

parser.add_argument(
"--rename-field",
type=str,
nargs=2,
action="append",
help='Rename field (e.g. "arxivid" to "eprint").',
)

parser.add_argument(
"--no-title",
action="store_true",
Expand Down Expand Up @@ -1317,6 +1325,14 @@ def GbibClean(cli_args: list[str] = None):
data, m = clever_merge(data)
merged = {**merged, **m}

# rename fields

if args.rename_field:
for oldfield, newfield in args.rename_field:
for entry in data:
if oldfield in entry:
entry[newfield] = entry.pop(oldfield)

# rename keys

if args.rename:
Expand Down
26 changes: 26 additions & 0 deletions tests/test_GbibClean.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,32 @@ def test_hidden_doi_arxiv(self):

os.remove(output)

def test_rename_field(self):
source = os.path.join(dirname, "library_hidden_doi_arxiv.bib")
output = os.path.join(dirname, "output.bib")
data = os.path.join(dirname, "library.yaml")
gbib.bibtex.GbibClean(["-f", "-o", output, source, "--rename-field", "arxivid", "eprint"])

with open(output) as file:
bib = bibtexparser.load(file, parser=bibtexparser.bparser.BibTexParser())

with open(data) as file:
data = yaml.load(file.read(), Loader=yaml.FullLoader)

for key in data:
data[key]["eprint"] = data[key].pop("arxivid")

for entry in bib.entries:
d = data[entry["ID"]]

for key in d:
if entry[key][0] == "{":
self.assertEqual("{" + str(d[key]) + "}", entry[key])
else:
self.assertEqual(str(d[key]), entry[key])

os.remove(output)

def test_missing_doi_arxiv(self):
source = os.path.join(dirname, "library_missing_doi_arxiv.bib")
output = os.path.join(dirname, "output.yaml")
Expand Down

0 comments on commit c043082

Please sign in to comment.