Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
122 commits
Select commit Hold shift + click to select a range
42cedca
refactor: Fix JSON decoding issues in generate_docs_for_chunk function
sumitjain236 Jul 28, 2024
7d8122c
refactor: Add allow_guest parameter to generate_bruno_file function
sumitjain236 Aug 2, 2024
2865d8c
refactor: Update UI layout and styling in ERDDoctypeAndAppModal, Your…
sumitjain236 Aug 2, 2024
0904c0a
refactor: Update UI layout and styling in CreateBranchModal, CreateOr…
sumitjain236 Aug 2, 2024
8c66ca4
refactor: Update UI layout and styling in AsyncDropdown
sumitjain236 Aug 9, 2024
4703258
refactor:Common Component for FormElement
sumitjain236 Aug 9, 2024
ac91f31
refactor: passed open to modal for reset the form when form get open
sumitjain236 Aug 9, 2024
c5614e2
refactor:Use of FormElement Component in this modals
sumitjain236 Aug 9, 2024
97b8339
refactor: Update UI layout and styling in multiple components
sumitjain236 Aug 9, 2024
2a10710
refactor:Make pages responsive and svg file added
sumitjain236 Aug 9, 2024
0c11a73
Merge pull request #60 from The-Commit-Company/UI-fixes-commit
sumitjain236 Aug 9, 2024
c2bbd88
refactor: ERD svg file
sumitjain236 Aug 12, 2024
eee413c
refactor: Update UI layout and styling in multiple components make it…
sumitjain236 Aug 30, 2024
04ca804
refactor: Update UI layout and styling in multiple components for res…
sumitjain236 Aug 30, 2024
7a2477d
refactor: Update UI layout and styling for responsiveness
sumitjain236 Aug 30, 2024
00effe2
refactor: Update UI layout and styling in Header and ProjectCard comp…
sumitjain236 Aug 30, 2024
72f359a
Refactor: use app_logo if app_logo_url is not present
sumitjain236 Sep 13, 2024
f6dd566
Refactor: Improve error handling in get_name_of_app function if repo …
sumitjain236 Sep 13, 2024
3c19d28
update readme because it was really needed
mngshm Sep 14, 2024
1d6b271
Merge pull request #65 from Mangeshrex/main
nikkothari22 Sep 14, 2024
656e880
Merge pull request #64 from The-Commit-Company/63-if-app_logo_url-is-…
sumitjain236 Sep 15, 2024
cb9df17
fix: API params are correctly loaded
nikkothari22 Sep 18, 2024
e9648b7
Merge pull request #67 from The-Commit-Company/fix-api-params
sumitjain236 Sep 19, 2024
bedcff5
feat:function for get_commands for apps
sumitjain236 Sep 20, 2024
6c00c36
Refactor: Add null check to prevent rendering ErrorBanner without err…
sumitjain236 Sep 20, 2024
2a4774c
Refactor: Add CommandContent component to APIList for displaying comm…
sumitjain236 Sep 20, 2024
7f7f566
feat: Add CommandContent component to APIList for displaying commands
sumitjain236 Sep 20, 2024
60207fd
Refactor: Update APIList component to use HiOutlineCommandLine icon f…
sumitjain236 Sep 20, 2024
002d808
refactor:show clickable link if help text content link
sumitjain236 Sep 20, 2024
b2839dc
fix:show mandatory fields
sumitjain236 Sep 20, 2024
5e42a08
Refactor: Update ParametersTable component to show mandatory fields
sumitjain236 Sep 20, 2024
19cbe36
Refactor: Update APIExplorer components to include Bench Commands
sumitjain236 Sep 20, 2024
d749cd5
Refactor: Change return type of 'ret' variable in get_project_app_com…
sumitjain236 Sep 20, 2024
18ff29c
Merge pull request #68 from The-Commit-Company/49-feature-request-sho…
sumitjain236 Sep 20, 2024
8aaac57
Update README.md
sumitjain236 Sep 20, 2024
7e6ff1a
Refactor: Add tooltip to display available bench commands in APIList …
sumitjain236 Sep 23, 2024
a799be7
Refactor: Add tooltip and API call functionality to APIDetails component
sumitjain236 Sep 23, 2024
cbc9707
Refactor: support for formData
sumitjain236 Sep 23, 2024
c90f382
Refactor: Reset form data in APIClientContent component
sumitjain236 Sep 23, 2024
c87dad0
fix:open app selection modal if apps is not present in location.state
sumitjain236 Sep 24, 2024
95a3587
Refactor: Simplify getting commands from app module
sumitjain236 Sep 24, 2024
2f58fc3
Refactor: Add padding to command name in CommandComponent
sumitjain236 Sep 24, 2024
f904ea7
feat:API for generating documentation for code_snippet
sumitjain236 Sep 25, 2024
fdfafc9
Refactor: Update APIDetails component to include Meta Documentation tab
sumitjain236 Sep 25, 2024
f327f73
feat: Add @uiw/react-md-editor package to dependencies
sumitjain236 Sep 25, 2024
8f449d5
Refactor: Remove unnecessary code in Header component and adjust styl…
sumitjain236 Sep 25, 2024
c11cae7
chore:Styling and layout fix
sumitjain236 Sep 25, 2024
b823339
fix:reset when modal close
sumitjain236 Sep 25, 2024
0e1cdfa
Merge pull request #69 from The-Commit-Company/com-33-allow-user-to-t…
sumitjain236 Sep 27, 2024
fff20b9
Merge branch 'com-34-allow-user-to-publish-documentations-from-commit…
sumitjain236 Sep 27, 2024
7c9072e
Merge pull request #70 from The-Commit-Company/main
sumitjain236 Sep 27, 2024
01121d2
wip
sumitjain236 Sep 27, 2024
16adedb
refactor:added last updated timestamp to each documentation
sumitjain236 Sep 27, 2024
f70a6d9
refactor: Update APIViewer and AppAPIViewer components
sumitjain236 Sep 27, 2024
d374b4d
fix:position from sticky to fixed
sumitjain236 Sep 27, 2024
f2b332b
refactor: Simplify APIDocumentation component and extract AllButton c…
sumitjain236 Sep 27, 2024
446c364
feat: Add Commit Branch Documentation doctype and related files
sumitjain236 Sep 29, 2024
b2958ac
chore: Update SpinnerLoader component to accept style prop and pass …
sumitjain236 Sep 29, 2024
068e488
feat:save documentation for project_branch or site_app
sumitjain236 Sep 29, 2024
c98a8f0
feat:get saved documentation for site app is exists
sumitjain236 Sep 29, 2024
319f76a
Merge pull request #72 from The-Commit-Company/com-34-allow-user-to-p…
sumitjain236 Sep 29, 2024
3c96d67
chore: API client and documentation components
sumitjain236 Sep 29, 2024
b31527e
fix:Cannot scroll all the way to the bottom in API list
sumitjain236 Sep 29, 2024
1b68eea
fix: Handle JSONDecodeError in generate_docs_for_chunk function
sumitjain236 Sep 29, 2024
721a414
fix: Update TooltipContent class in APIDocumentation component
sumitjain236 Sep 29, 2024
60c6223
fix: Handle ModuleNotFoundError in get_site_app_commands function and…
sumitjain236 Oct 4, 2024
6fed939
fix:endpoint max Character length
sumitjain236 Oct 4, 2024
c836d8d
Update README.md
Pardeshi-Aditya Oct 4, 2024
8ddb624
Merge pull request #73 from Pardeshi-Aditya/main
sumitjain236 Oct 19, 2024
a64bf8e
chore:Publish status added
sumitjain236 Oct 29, 2024
d1e40c0
feat:Check Component
sumitjain236 Oct 29, 2024
c71daa3
feat: Add Commit Docs related files
sumitjain236 Oct 29, 2024
2f4dc77
feat: Add published_route to API documentation and update Checkbox la…
sumitjain236 Nov 1, 2024
67b7766
feat:CreatableSelect Component
sumitjain236 Nov 1, 2024
4ee3ff2
feat: Add published field to Commit Docs and update API documentation…
sumitjain236 Nov 1, 2024
4bfb4c0
chore
sumitjain236 Nov 1, 2024
940a1cc
feat:Publish Documentation API
sumitjain236 Nov 1, 2024
b2d3968
fix: Ensure consistent return values in get_documentation_from_branch…
sumitjain236 Nov 3, 2024
f35d3ce
feat: Add new TypeScript interfaces for complete commit module
sumitjain236 Nov 3, 2024
98ddc95
feat: Add API endpoint to retrieve Commit Docs details and sidebar,fo…
sumitjain236 Nov 3, 2024
fecaa25
feat: Add DynamicIcon component for lazy loading icons
sumitjain236 Nov 3, 2024
eb05aec
fix: Handle invalid JSON format in documentation entries in get_apis_…
sumitjain236 Nov 4, 2024
b6a5416
feat: Expand icon library support in DynamicIcon component
sumitjain236 Nov 4, 2024
d6e975d
feat: Enhance sidebar item retrieval with support for nested Group Pages
sumitjain236 Nov 4, 2024
8418259
feat: Add new fields for company name, Slack, Telegram, and YouTube U…
sumitjain236 Nov 9, 2024
888db0d
feat: Add framer-motion library for enhanced animations in the dashboard
sumitjain236 Nov 9, 2024
c261d2e
feat: Add a 404 Page Not Found component with animations and navigation
sumitjain236 Nov 9, 2024
b846aff
feat: Introduce new types for Docs structure including sidebar, navba…
sumitjain236 Nov 9, 2024
a53a3ad
feat: Add ViewDocs component for displaying document details with sid…
sumitjain236 Nov 9, 2024
05608e3
feat: Add Sidebar component for document navigation with expandable g…
sumitjain236 Nov 9, 2024
95521ea
feat: Add Navbar component for document navigation with search functi…
sumitjain236 Nov 9, 2024
7dffe69
feat: Add Footer component with dynamic sections and social media links
sumitjain236 Nov 9, 2024
a9693f9
feat: Enhance Navbar component with conditional styling for primary b…
sumitjain236 Nov 9, 2024
fb42d09
refactor: Remove commented-out print statements for cleaner code
sumitjain236 Nov 9, 2024
406480f
fix: Update MarkdownRenderer to handle TypeScript errors with remark …
sumitjain236 Nov 9, 2024
e02f222
feat: Refactor CommitDocs to use before_insert and enhance sidebar fu…
sumitjain236 Nov 15, 2024
c26ff18
feat: Add ErrorBanner component to Projects for improved error handli…
sumitjain236 Nov 15, 2024
b94907a
fix: Update documentation generation to use triple backticks for code…
sumitjain236 Dec 6, 2024
4ea23ba
feat: get commit page API
sumitjain236 Dec 6, 2024
ae09455
feat: Add MDX support to Vite configuration and update dependencies
sumitjain236 Dec 6, 2024
71f13f9
feat: MDXRenderer Component for rendering MDX
sumitjain236 Dec 6, 2024
01d7c0e
feat: Add CustomCodeBlock and CustomHeading components for enhanced M…
sumitjain236 Dec 6, 2024
7e5b6c0
feat: Docs Page with sidebar, navbar, footer, Pagecontent
sumitjain236 Dec 6, 2024
379a41b
feat: Add OnThisPage component for table of contents navigation
sumitjain236 Dec 6, 2024
6254e68
feat: Implement DocsPage component and route navigation for commit do…
sumitjain236 Dec 10, 2024
b7c963c
feat: Enhance ViewDocs component to support pageID and simplify state…
sumitjain236 Dec 10, 2024
95b84a1
feat: enhance CustomHeading component with scroll behavior
sumitjain236 Dec 10, 2024
c246ccc
feat: update Commit Docs Page and related components for improved gue…
sumitjain236 Dec 20, 2024
14a86e9
feat: replace react-icons with lucide-react icons for consistency and…
sumitjain236 Dec 20, 2024
a37c610
feat:lazy load the components
sumitjain236 Dec 20, 2024
95077ff
feat: refactor YourAppAPIExplorer and YourApps components to use cust…
sumitjain236 Dec 20, 2024
63fb399
feat: add preload link for fetching project list with branches in das…
sumitjain236 Dec 20, 2024
ae6cead
feat: add API for fetching all published commit docs details and refa…
sumitjain236 Dec 20, 2024
72a5e18
style: remove background color from MarkdownRenderer for improved sty…
sumitjain236 Dec 20, 2024
9dc69b8
feat: enhance MarkdownRenderer with rehype-pretty-code and improve Cu…
sumitjain236 Dec 24, 2024
2f95fae
Merge pull request #75 from The-Commit-Company/improve-performance
sumitjain236 Dec 24, 2024
6cc7f47
chore: update vite version to ^6.0.5 in package.json
sumitjain236 Dec 24, 2024
f7f4155
feat: add Milkdown MarkdownEditor component and related styles
sumitjain236 Dec 28, 2024
49a2540
feat: add FormHelperText component and refactor APIClientContent and …
sumitjain236 Dec 28, 2024
a756fc8
feat: add DocsPageForm and EditorComponent for enhanced documentation…
sumitjain236 Dec 28, 2024
7d2c684
feat: add Renderer component for displaying documentation with naviga…
sumitjain236 Dec 28, 2024
0720f02
Merge pull request #76 from The-Commit-Company/markdown-editor
sumitjain236 Dec 28, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 41 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,42 @@
# commit
## commit
<p align="center">
<a href="https://github.com/The-Commit-Company/commit">
<img src="dashboard/src/assets/commit-logo.png" alt="Commit logo" height="100" />
</a>

The Commit Company
<h3 align="center">commit</h3>
<p align="center">Developer tooling for the Frappeverse 🪐
<br />
<br />
<a href="https://frappecloud.com/marketplace/apps/commit"><strong>Install on Frappe Cloud»</strong></a>
<br />
<br />
<a href="https://commit.frappe.cloud/"><strong>Learn More »</strong></a>
<br />
<br />
<a href="https://github.com/The-Commit-Company/commit/issues">Issues</a>
.
<a href="https://github.com/sponsors/The-Commit-Company?frequency=one-time">Sponsor Us!</a>
</p>
</p>
<p align="center">
<a href="https://github.com/The-Commit-Company/commit/blob/main/LICENSE">
<img alt="license" src="https://img.shields.io/badge/license-AGPLv3-blue">
</a>
<a href="https://github.com/The-Commit-Company/commit/stargazers"><img src="https://img.shields.io/github/stars/The-Commit-Company/commit" alt="Github Stars"></a>
<a href="https://github.com/The-Commit-Company/commit/pulse"><img src="https://img.shields.io/github/commit-activity/m/The-Commit-Company/commit" alt="Commits-per-month"></a>
</p>

# [commit](https://commit.frappe.cloud/)

Born out of a need to improve developer tooling for Frappe, "Commit" allows you to visualize your app's database schema and view all it's APIs - improving developer productivity and security of your critical applications.

## Basic Installation

The below guide assumes that you already have a working Frappe and Bench installation. If you do not have it, then please head over to [Official Installation Guide](https://frappeframework.com/docs/user/en/installation).

Go ahead and create a fresh new bench

- `bench init commit`
- `bench get-app https://github.com/The-commit-company/commit`
- `bench new-site <preferred-site-url>`
- `bench --site <site-url> install-app commit`
17 changes: 15 additions & 2 deletions commit/api/api_explorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,24 @@ def get_apis_for_project(project_branch: str):

apis = json.loads(branch_doc.whitelisted_apis).get("apis", []) if branch_doc.whitelisted_apis else []
documentation = json.loads(branch_doc.documentation).get("apis", []) if branch_doc.documentation else []
print('documentation', len(documentation))
for api in apis:
# find the documentation for the api whose function_name equals to name and path same as path
for doc in documentation:
if isinstance(doc, str):
try:
doc = json.loads(doc)
except json.JSONDecodeError:
frappe.log_error(f"Invalid JSON format in documentation entry: {doc}", "Commit Docs Error")
continue

if doc.get("function_name") == api.get("name") and doc.get("path") == api.get("api_path"):
api["documentation"] = doc.get("documentation")
api["last_updated"] = doc.get("last_updated")
api["is_published"] = doc.get("is_published", 0)
api["published_on"] = doc.get("published_on", None)
api["published_by"] = doc.get("published_by", None)
api['publish_id'] = doc.get('publish_id', None)
api['published_route'] = doc.get('published_route', None)
break

app_name, organization, app_logo = frappe.db.get_value("Commit Project", branch_doc.project, ["app_name", "org", "image"])
Expand All @@ -33,7 +45,8 @@ def get_apis_for_project(project_branch: str):
"org_logo": org_logo,
"branch_name": branch_doc.branch_name,
"project_branch": branch_doc.name,
"last_updated": branch_doc.last_fetched
"last_updated": branch_doc.last_fetched,
'path_to_folder':branch_doc.path_to_folder
}


Expand Down
2 changes: 1 addition & 1 deletion commit/api/bruno.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import frappe

@frappe.whitelist()
@frappe.whitelist(allow_guest=True)
def generate_bruno_file(data, return_type='download'):
request_data = frappe.parse_json(data)
"""
Expand Down
13 changes: 8 additions & 5 deletions commit/api/code_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,23 @@ def get_name_of_app(organization, repo):
'''
Get name of app from repo
'''
type = None
file_type = None
app_name = None
root_files = get_all_files_in_repo(access_token, organization, repo)
if type(root_files) == dict and root_files.get("message", "") == "Not Found":
return frappe.throw(f'Repository {repo} not found in organization {organization}')

for file in root_files:
if file["name"] == "pyproject.toml":
type = "pyproject.toml"
file_type = "pyproject.toml"
break
elif file["name"] == "setup.py":
type = "setup.py"
file_type = "setup.py"
break

if type == "pyproject.toml":
if file_type == "pyproject.toml":
app_name = get_app_name_from_pyproject_toml(organization, repo)
elif type == "setup.py":
elif file_type == "setup.py":
app_name = get_app_name_from_setup_py(organization, repo)

return app_name
Expand Down
167 changes: 153 additions & 14 deletions commit/api/generate_documentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import re
from commit.commit.doctype.open_ai_settings.open_ai_settings import open_ai_call
import frappe
from commit.api.api_explorer import get_file_content_from_path


def generate_docs_for_apis(api_definitions):
Expand All @@ -12,7 +13,6 @@ def generate_docs_for_apis(api_definitions):

for chunk in chunks:
chunk_docs = generate_docs_for_chunk(chunk)
# print("Chunk Docs:", chunk_docs)
if chunk_docs:
all_docs.extend(chunk_docs)
else:
Expand Down Expand Up @@ -61,24 +61,22 @@ def generate_docs_for_chunk(api_chunk):
"content": (
"You are an expert documentation generator. Create detailed and comprehensive documentation "
"for the code provided below in Markdown format. Each function should have the following sections:\n\n"
"- **(api[Function Name])**\n"
"- **Description**: Detailed description of what the function does and what it is used for \n"
"- **Parameters**: List of parameters with their types, descriptions, and indicate which are mandatory or optional\n"
"- **Return Type**: Type and description of the return value\n"
"- **Examples**: Code examples demonstrating how to use the function (enclosed in triple backticks ``````).\n\n"
"- # [Function Name] (as heading 1)\n"
"- ## Description: Detailed description of what the function does and what it is used for \n"
"- ## Parameters: List of parameters with their types, descriptions, and indicate which are mandatory or optional\n"
"- ## Return Type: Type and description of the return value\n"
"- ## Examples\n Provide code examples demonstrating how to use the function, enclosed in triple backticks (``````).\n\n"
"The response should be a valid JSON list of objects formatted as follows: "
"{function_name: <function_name>, path: <path>, documentation: <documentation in Markdown>}.\n"
"Ensure the response is in JSON format only, enclosed in triple backticks, and does not include `---`."
"{function_name: <function_name>, path: <path>, last_updated:<last_updated>, documentation: <documentation in Markdown>}.\n"
"Ensure the response is in valid JSON format only, enclosed in triple backticks, and does not include `---`."
)
}
]

last_updated = frappe.utils.now()
for api in api_chunk:
user_message = f"function name: {api['function_name']}, path: {api['path']}, code:\n{api['code']}"
user_message = f"function name: {api['function_name']}, path: {api['path']}, last_updated:{last_updated} ,code:\n{api['code']}"
messages.append({"role": "user", "content": user_message})

# print("Raw Response:\n", response_text) # Log raw response for debugging

response_text = open_ai_call(messages)

cleaned_response = clean_response(response_text)
Expand All @@ -89,14 +87,155 @@ def generate_docs_for_chunk(api_chunk):
return cleaned_response
# If cleaned_response is a string, attempt to decode it as JSON
elif isinstance(cleaned_response, str):
return json.loads(cleaned_response)
return json.loads(cleaned_response, strict=False)
else:
# Handle other unexpected types if necessary
print("Unexpected type of cleaned_response:", type(cleaned_response))
return []
except json.JSONDecodeError as e:
print("JSON Decode Error:", e)
print("Cleaned Response:\n", cleaned_response)
try:
# Attempt to fix common issues like single quotes or trailing commas
cleaned_response = cleaned_response.replace("'", '"')
return json.loads(cleaned_response, strict=False)
except json.JSONDecodeError as e:
print("Second JSON Decode Error:", e)
return []
# return cleaned_response

def generate_documentation_for_api_snippet(api_path:str,code_snippet:str):
messages = [
{
"role": "system",
"content": (
"You are an expert documentation generator. Create detailed and comprehensive documentation "
"for the code provided below in Markdown format. Each function should have the following sections:\n\n"
"- # [Function Name] (as heading 1)\n"
"- ## Description\n Provide a detailed description of what the function does and what it is used for.\n"
"- ## Parameters\n List of parameters with their types, descriptions, and indicate which are mandatory or optional.\n"
"- ## Return Type\n Specify the type and description of the return value.\n"
"- ## Examples\n Provide code examples demonstrating how to use the function, enclosed in triple backticks (``````).\n\n"
"The response should be a valid JSON formatted as follows: "
"{function_name: <function_name>, path: <path>, last_updated:<last_updated>, documentation: <documentation in Markdown>}.\n"
"Ensure the response is in valid JSON format only, and does not include `---`."
)
}
]

user_message = f"api path: {api_path}, last_updated:{frappe.utils.now()}, code:\n{code_snippet}"
if not code_snippet:
return []
messages.append({"role": "user", "content": user_message})

response_text = open_ai_call(messages)

cleaned_response = response_text

try:
# Check if cleaned_response is already a list (or the expected type)
if isinstance(cleaned_response, list):
return cleaned_response
# If cleaned_response is a string, attempt to decode it as JSON
elif isinstance(cleaned_response, str):
return json.loads(cleaned_response, strict=False)
else:
# Handle other unexpected types if necessary
print("Unexpected type of cleaned_response:", type(cleaned_response))
return []
except json.JSONDecodeError as e:
print("JSON Decode Error:", e)
print("Cleaned Response:\n", cleaned_response)
try:
# Attempt to fix common issues like single quotes or trailing commas
cleaned_response = cleaned_response.replace("'", '"')
return json.loads(cleaned_response, strict=False)
except json.JSONDecodeError as e:
print("Second JSON Decode Error:", e)
return []

# return cleaned_response
@frappe.whitelist()
def get_documentation_for_api(project_branch: str, file_path: str,block_start: int, block_end: int,endpoint:str,viewer_type:str = 'app'):
code_snippet = get_file_content_from_path(project_branch, file_path,block_start, block_end,viewer_type)
api_path = endpoint
return generate_documentation_for_api_snippet(api_path, code_snippet)

@frappe.whitelist()
def save_documentation(project_branch:str,endpoint:str,documentation:str,viewer_type:str = 'app'):
# Save the documentation to the project branch
# 1. Check for viewer_type app or project
# 2. If viewer_type is app, then check the document is already present in Commit Branch Documentation doctype
# 3. If document present then loop over documentation check if the function_name and path matches then update the documentation else create a new dict and append to the documentation
# 4. If document not present then create a new document and append the documentation
# 5. If viewer_type is project then check the document is already present in Commit Project Branch doctype
# 6. If document present then loop over documentation check if the function_name and path matches then update the documentation else create a new dict and append to the documentation
# 7. If document not present then create a new document and append the documentation

if viewer_type == "app":
# Check if the document is already present in Commit Branch Documentation doctype
save_documentation_for_site_app(project_branch, endpoint, documentation)
else:
save_documentation_for_project_branch(project_branch, endpoint, documentation)

def save_documentation_for_project_branch(project_branch:str,endpoint:str,documentation:str):

doc = frappe.get_doc("Commit Project Branch", project_branch)
docs = json.loads(doc.documentation) if doc.documentation else {}
apis = docs.get("apis", [])

# apis is list of dict with keys function_name, path, last_updated, documentation
# loop over apis and check if function_name and path matches then update the documentation else create a new dict and append to the documentation
found = False
for api in apis:
if api.get("function_name") == endpoint.split(".")[-1] and api.get("path") == endpoint:
api["documentation"] = documentation
api["last_updated"] = frappe.utils.now()
found = True
break
if not found:
apis.append({
"function_name": endpoint.split(".")[-1],
"path": endpoint,
"last_updated": frappe.utils.now(),
"documentation": documentation
})

doc.documentation = json.dumps({"apis": apis})
doc.save()

def save_documentation_for_site_app(project_branch:str,endpoint:str,documentation:str):

if frappe.db.exists("Commit Branch Documentation",project_branch):
doc = frappe.get_doc("Commit Branch Documentation", project_branch)
docs = json.loads(doc.documentation) if doc.documentation else {}
apis = docs.get("apis", [])

# apis is list of dict with keys function_name, path, last_updated, documentation
# loop over apis and check if function_name and path matches then update the documentation else create a new dict and append to the documentation
found = False
for api in apis:
if api.get("function_name") == endpoint.split(".")[-1] and api.get("path") == endpoint:
api["documentation"] = documentation
api["last_updated"] = frappe.utils.now()
found = True
break
if not found:
apis.append({
"function_name": endpoint.split(".")[-1],
"path": endpoint,
"last_updated": frappe.utils.now(),
"documentation": documentation
})
doc.documentation = json.dumps({"apis": apis})
doc.save()
else:
# Create a new document and append the documentation
doc = frappe.new_doc("Commit Branch Documentation")
doc.app = project_branch
doc.documentation = json.dumps({"apis": [{
"function_name": endpoint.split(".")[-1],
"path": endpoint,
"last_updated": frappe.utils.now(),
"documentation": documentation
}]})
doc.save()
Loading