gen-api-v1-docs.ps1 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # This script generates API documentation using swaggo/swag
  2. # For more details, check the docs:
  3. # * https://usememos.com/docs/contribution/development
  4. # * https://github.com/usememos/memos/blob/main/docs/api/documentation.md
  5. # Requirements:
  6. # * go
  7. # swag is configured mainly via gen-api-v1-docs.cfg file.
  8. # Usage:
  9. # ./scripts/gen-api-v1-docs.ps1
  10. foreach ($dir in @(".", "../")) {
  11. if (Test-Path (Join-Path $dir ".gitignore")) {
  12. $repoRoot = (Resolve-Path $dir).Path
  13. break
  14. }
  15. }
  16. Set-Location $repoRoot
  17. Write-Host "Parsing gen-api-v1-docs.cfg..."
  18. foreach ($line in (Get-Content "$repoRoot\scripts\gen-api-v1-docs.cfg" )) {
  19. if ($line.Trim().StartsWith('#')) {
  20. continue
  21. }
  22. $name, $value = $line.split('=')
  23. if ([string]::IsNullOrWhiteSpace($name)) {
  24. continue
  25. }
  26. Set-Content env:\$name $value
  27. }
  28. Write-Host "API directories: $env:SWAG_API_DIRS" -f Cyan
  29. Write-Host "Output directory: $env:SWAG_OUTPUT" -f Cyan
  30. Write-Host "General info: $env:SWAG_GENERAL_INFO" -f Cyan
  31. $swag = (Get-Command swag -ErrorAction SilentlyContinue).Path
  32. if (-not $swag) {
  33. foreach ($path in @((Join-Path $HOME "go/bin"), (Join-Path $env:GOPATH "/bin"))) {
  34. $swag = Join-Path (Resolve-Path $path).Path "swag.exe"
  35. if (Test-Path $swag) {
  36. break
  37. }
  38. }
  39. }
  40. if (-not (Test-Path $swag)) {
  41. Write-Host "Swag is not installed. Installing..." -f Magenta
  42. go install github.com/swaggo/swag/cmd/swag@latest
  43. }
  44. $generalInfoPath = (Split-Path (Resolve-Path $env:SWAG_GENERAL_INFO -Relative) -Parent)
  45. $apiDirs = $env:SWAG_API_DIRS -split ',' | ForEach-Object { "$(Resolve-Path $_ -Relative)" }
  46. $swagFmtDirs = $generalInfoPath + "," + $($apiDirs -join ",")
  47. Write-Host "Formatting comments via ``swag fmt --dir `"$swagFmtDirs`"``..." -f Magenta
  48. &$swag fmt --dir "`"${swagFmtDirs}`""
  49. $goFmtDirs = $swagFmtDirs -split ',' | ForEach-Object { "`"$($_)`"" }
  50. # This is just in case swag fmt do something non-conforming to go fmt
  51. Write-Host "Formatting code via ``go fmt ${goFmtDirs}``..." -f Magenta
  52. go fmt ${goFmtDirs}
  53. Write-Host "Generating Swagger API documentation..." -f Magenta
  54. &$swag init --output $env:SWAG_OUTPUT --outputTypes $env:SWAG_OUTPUT_TYPES --generalInfo $env:SWAG_GENERAL_INFO --dir "./,${env:SWAG_API_DIRS}"
  55. if ($LASTEXITCODE -ne 0) {
  56. Write-Host "Failed to generate API documentation!" -f Red
  57. exit $LASTEXITCODE
  58. }
  59. Write-Host "API documentation updated!" -f Green