Skip to content

Commit 7180f5c

Browse files
authored
feat: support new folders structure (#434)
openfoodfacts/openfoodfacts-server@2b2d85f added a new structure to taxonomy folders. This is a quick fix to support it
1 parent f010f31 commit 7180f5c

File tree

6 files changed

+37
-18
lines changed

6 files changed

+37
-18
lines changed

backend/editor/api.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,7 @@ async def import_from_github(
374374
taxonomy = TaxonomyGraph(branch, taxonomy_name)
375375

376376
if not taxonomy.is_valid_branch_name():
377-
raise HTTPException(status_code=422, detail="branch_name: Enter a valid branch name!")
377+
raise HTTPException(status_code=422, detail="branch_name: Enter a valid branch name!")
378378
if await taxonomy.does_project_exist():
379379
raise HTTPException(status_code=409, detail="Project already exists!")
380380
if not await taxonomy.is_branch_unique(from_github=True):

backend/editor/entries.py

+16-8
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
Database helper functions for API
33
"""
44

5+
import logging
56
import re
67
import shutil
78
import tempfile
@@ -15,7 +16,7 @@
1516
from openfoodfacts_taxonomy_parser import unparser # Unparser for taxonomies
1617
from openfoodfacts_taxonomy_parser import utils as parser_utils
1718

18-
from . import settings
19+
from . import settings, utils
1920
from .controllers.node_controller import create_entry_node
2021
from .controllers.project_controller import create_project, edit_project, get_project
2122
from .exceptions import GithubBranchExistsError # Custom exceptions
@@ -33,7 +34,8 @@
3334
)
3435
from .models.node_models import EntryNodeCreate
3536
from .models.project_models import ProjectCreate, ProjectEdit, ProjectStatus
36-
from .utils import file_cleanup
37+
38+
log = logging.getLogger(__name__)
3739

3840

3941
async def async_list(async_iterable):
@@ -48,6 +50,10 @@ def __init__(self, branch_name, taxonomy_name):
4850
self.branch_name = branch_name
4951
self.project_name = "p_" + taxonomy_name + "_" + branch_name
5052

53+
@property
54+
def taxonomy_path_in_repository(self):
55+
return utils.taxonomy_path_in_repository(self.taxonomy_name)
56+
5157
def get_label(self, id):
5258
"""
5359
Helper function for getting the label for a given id
@@ -82,13 +88,13 @@ async def get_local_taxonomy_file(self, tmpdir: str, uploadfile: UploadFile):
8288

8389
async def get_github_taxonomy_file(self, tmpdir: str):
8490
async with TransactionCtx():
85-
filename = f"{self.taxonomy_name}.txt"
86-
filepath = f"{tmpdir}/{filename}"
87-
base_url = (
88-
"https://raw.githubusercontent.com/" + settings.repo_uri + "/main/taxonomies/"
91+
filepath = f"{tmpdir}/{self.taxonomy_name}.txt"
92+
target_url = (
93+
f"https://raw.githubusercontent.com/{settings.repo_uri}"
94+
f"/main/{self.taxonomy_path_in_repository}"
8995
)
9096
try:
91-
await run_in_threadpool(urllib.request.urlretrieve, base_url + filename, filepath)
97+
await run_in_threadpool(urllib.request.urlretrieve, target_url, filepath)
9298
github_object = GithubOperations(self.taxonomy_name, self.branch_name)
9399
commit_sha = (await github_object.get_branch("main")).commit.sha
94100
file_sha = await github_object.get_file_sha()
@@ -131,6 +137,7 @@ async def get_and_parse_taxonomy(self, uploadfile: UploadFile | None = None):
131137
# add an error node so we can display it with errors in the app
132138
async with TransactionCtx():
133139
await edit_project(self.project_name, ProjectEdit(status=ProjectStatus.FAILED))
140+
log.exception(e)
134141
raise e
135142

136143
async def import_taxonomy(
@@ -169,9 +176,10 @@ def dump_taxonomy(self, background_tasks: BackgroundTasks):
169176
# Dump taxonomy with given file name and branch name
170177
unparser_object(filename, self.branch_name, self.taxonomy_name)
171178
# Program file removal in the background
172-
background_tasks.add_task(file_cleanup, filename)
179+
background_tasks.add_task(utils.file_cleanup, filename)
173180
return filename
174181
except Exception as e:
182+
log.exception(e)
175183
raise TaxonomyUnparsingError() from e
176184

177185
async def file_export(self, background_tasks: BackgroundTasks):

backend/editor/github_functions.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
PullRequest,
1717
)
1818

19-
from . import settings
19+
from . import settings, utils
2020

2121

2222
class GithubOperations:
@@ -26,6 +26,10 @@ def __init__(self, taxonomy_name: str, branch_name: str):
2626
self.taxonomy_name = taxonomy_name
2727
self.branch_name = branch_name
2828

29+
@property
30+
def taxonomy_path_in_repository(self):
31+
return utils.taxonomy_path_in_repository(self.taxonomy_name)
32+
2933
@cached_property
3034
def repo_info(self) -> tuple[str, str]:
3135
repo_uri = settings.repo_uri
@@ -68,10 +72,9 @@ async def get_file_sha(self) -> str:
6872
"""
6973
Get the file SHA from the 'main' branch in the "openfoodfacts-server" repo
7074
"""
71-
github_filepath = f"taxonomies/{self.taxonomy_name}.txt"
7275
file_contents: ContentFile = (
7376
await self.connection.rest.repos.async_get_content(
74-
*self.repo_info, path=github_filepath
77+
*self.repo_info, path=self.taxonomy_path_in_repository
7578
)
7679
).parsed_data
7780

@@ -90,8 +93,7 @@ async def update_file(self, filename: str, file_sha: str, author_name) -> FileCo
9093
Update the taxonomy txt file edited by user using the Taxonomy Editor
9194
"""
9295
# Find taxonomy text file to be updated
93-
github_filepath = f"taxonomies/{self.taxonomy_name}.txt"
94-
commit_message = f"Update {self.taxonomy_name}.txt"
96+
commit_message = f"Update {self.taxonomy_path_in_repository}"
9597
author = {"name": author_name, "email": "[email protected]"}
9698
try:
9799
with open(filename, "r") as f:
@@ -103,7 +105,7 @@ async def update_file(self, filename: str, file_sha: str, author_name) -> FileCo
103105
return (
104106
await self.connection.rest.repos.async_create_or_update_file_contents(
105107
*self.repo_info,
106-
path=github_filepath,
108+
path=self.taxonomy_path_in_repository,
107109
message=commit_message,
108110
content=base64.b64encode(new_file_contents.encode("utf-8")),
109111
sha=file_sha,

backend/editor/utils.py

+9
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,12 @@ def file_cleanup(filepath):
1212
os.remove(filepath)
1313
except FileNotFoundError:
1414
log.warn(f"Taxonomy file {filepath} not found for deletion")
15+
16+
17+
def taxonomy_path_in_repository(taxonomy_name):
18+
"""Helper function to get the path of a taxonomy in the repository"""
19+
path = taxonomy_name
20+
# hacky for now until we restructure better
21+
if path in ("food_ingredients", "food_categories"):
22+
path = path.replace("_", "/")
23+
return f"taxonomies/{path}.txt"

taxonomy-editor-frontend/src/constants.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,11 @@ export const TAXONOMY_NAMES = [
2727
"Additives",
2828
"Allergens",
2929
"Amino Acids",
30-
"Categories",
30+
"Food Categories",
3131
"Data Quality",
3232
"Food Groups",
3333
"Improvements",
34-
"Ingredients",
34+
"Food Ingredients",
3535
"Ingredients Analysis",
3636
"Ingredients Processing",
3737
"Labels",

taxonomy-editor-frontend/src/pages/startproject/index.tsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ export const StartProject = () => {
3232

3333
const findDefaultBranchName = useCallback(() => {
3434
if (taxonomyName === "" || ownerName === "") return "";
35-
return `${taxonomyName.toLowerCase()}_${ownerName
35+
return `${toSnakeCase(taxonomyName.toLowerCase())}_${ownerName
3636
.replace(" ", "")
3737
.toLowerCase()}_${Math.floor(Date.now() / 1000)}`;
3838
}, [ownerName, taxonomyName]);

0 commit comments

Comments
 (0)