├── .github ├── FUNDING.yml └── workflows │ └── build.yml ├── .gitignore ├── .travis.yml ├── LICENSE.txt ├── Makefile ├── README.adoc ├── build.sbt ├── project ├── build.properties └── plugins.sbt └── src └── main └── scala ├── Plugin.scala └── tobiasroeser └── gitbucket └── asciidoctor ├── AsciidoctorJgitIncludeProcessor.scala └── AsciidoctorRenderer.scala /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: lefou 4 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | pull_request: 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - name: Checkout 10 | uses: actions/checkout@v3 11 | 12 | - name: Setup Java 8 13 | uses: actions/setup-java@v3 14 | with: 15 | java-version: '8' 16 | distribution: 'temurin' 17 | cache: 'sbt' 18 | 19 | - name: Build 20 | run: sbt compile assembly 21 | 22 | # Uploads information to the GitHub dependency graph and unblocking Dependabot alerts for the repository 23 | - name: Upload dependency graph 24 | if: github.repository == 'asciidoctor/gitbucket-asciidoctor-plugin' && github.ref == 'refs/heads/main' 25 | uses: scalacenter/sbt-dependency-submission@ab086b50c947c9774b70f39fc7f6e20ca2706c91 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .cache 2 | .cache-main 3 | .classpath 4 | .project 5 | .settings/ 6 | bin/ 7 | project/project/ 8 | project/target/ 9 | target/ 10 | 11 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: scala 4 | 5 | jdk: 6 | - openjdk8 7 | 8 | scala: 9 | - 2.13.0 10 | 11 | script: make travis 12 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | VERSION = 1.1.0 2 | GITBUCKET_VERSION = 4.32.0 3 | SCALA_BIN_VERSION=2.13 4 | 5 | .PHONY: help # List of targets with descriptions 6 | help: 7 | @grep '^\.PHONY: .* #' Makefile | sed 's/\.PHONY: \(.*\) # \(.*\)/\1\t\2/' | expand -t20 8 | 9 | .PHONY: clean # Clean output files (target dir) 10 | clean: 11 | rm -rf target/ project/target/ 12 | 13 | .PHONY: build # Build the project and the plugin package 14 | build: 15 | sbt assembly 16 | 17 | target/gitbucket-$(GITBUCKET_VERSION)-asciidoctor-plugin-$(VERSION).jar: build 18 | cp target/scala-$(SCALA_BIN_VERSION)/gitbucket-asciidoctor-plugin-$(VERSION).jar target/gitbucket-$(GITBUCKET_VERSION)-asciidoctor-plugin-$(VERSION).jar 19 | 20 | stamped-jar: target/gitbucket-$(GITBUCKET_VERSION)-asciidoctor-plugin-$(VERSION).jar 21 | 22 | .PHONY: travis # Build on travis 23 | travis: build 24 | 25 | target/gitbucket-${GITBUCKET_VERSION}.war: 26 | mkdir -p target 27 | wget https://github.com/gitbucket/gitbucket/releases/download/$(GITBUCKET_VERSION)/gitbucket.war -O target/gitbucket-$(GITBUCKET_VERSION).war 28 | 29 | .PHONY: localServer # Start a local gitbucket server with the plugin installed 30 | localServer: stamped-jar target/gitbucket-$(GITBUCKET_VERSION).war 31 | mkdir -p target/DATA/plugins 32 | rm -rf target/DATA/plugins/* 33 | cp target/gitbucket-$(GITBUCKET_VERSION)-asciidoctor-plugin-$(VERSION).jar target/DATA/plugins 34 | java -jar target/gitbucket-$(GITBUCKET_VERSION).war --gitbucket.home=target/DATA 35 | -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | = gitbucket-asciidoctor-plugin 2 | :plugin-version: 1.1.0 3 | :scala-version: 2.13 4 | :gitbucket-bincompat-version: 4.32.0 5 | :link-github: https://github.com/asciidoctor/gitbucket-asciidoctor-plugin 6 | 7 | 8 | image:{link-github}/actions/workflows/build.yml/badge.svg["Build Status (build.yml)", link="{link-github}/actions/workflows/build.yml"] 9 | image:https://badges.gitter.im/asciidoctor/gitbucket-asciidoctor-plugin.svg["Gitter Chat", link="https://gitter.im/asciidoctor/gitbucket-asciidoctor-plugin"] 10 | 11 | A https://github.com/gitbucket/gitbucket[GitBucket] plug-in that provides AsciiDoc rendering capabilities. 12 | All `.adoc` (and also the deprecated `.asciidoc` and `.ad` suffix) files will be automatically rendered as AsciiDoc, supporting most features of the http://asciidoctor.org/[Asciidoctor project], including rendering of a table of contents. 13 | 14 | == Download 15 | 16 | You can download a precompiled version from the {link-github}/releases[Release page]. 17 | 18 | 19 | == Build from source 20 | 21 | .With sbt 22 | ---- 23 | sbt assembly 24 | ---- 25 | 26 | .Or with GNU Make 27 | ---- 28 | make build 29 | ---- 30 | 31 | You will find the packages plugin under `target/scala_2.13/gitbucket-asciidoctor-plugin-gitbucket_{gitbucket-bincompat-version}-{plugin-version}.jar` 32 | 33 | 34 | == Installation 35 | 36 | Download `gitbucket-asciidoctor-plugin-gitbucket_{gitbucket-bincompat-version}-{plugin-version}.jar` 37 | or build the assembly package JAR file from source and copy it into `GITBUCKET_HOME/plugins`. 38 | If you have older versions of this plugin in this directory, you must delete them. 39 | Then restart GitBucket. 40 | That's it. 41 | 42 | == Local Test Server 43 | 44 | You can start a local GitBucket instance with this plugin already installed by running: 45 | 46 | ---- 47 | make localServer 48 | ---- 49 | 50 | Point your browser to http://localhost:8080. The administrator login is root/root. 51 | 52 | 53 | == Configuration 54 | 55 | === Asciidoctor builtin attributes 56 | 57 | You can tweak the asciidoctor rendering engine by customizing the 58 | http://asciidoctor.org/docs/user-manual/#builtin-attributes[builtin attributes]. Simple edit the properties file at `GITBUCKET_HOME/asciidoctor.properties`. 59 | 60 | .Example: Set `toc` attribute in the `GITBUCKET_HOME/asciidoctor.properties` file 61 | [source,properties] 62 | ---- 63 | toc=preamble 64 | ---- 65 | 66 | 67 | == License 68 | 69 | This plugin is published under the Apache License, version 2.0. 70 | 71 | == ChangeLog 72 | 73 | === gitbucket-asciidoctor-plugin 1.1.0 - 2019-11-19 74 | 75 | * Support fot GitBucket 4.32.0 76 | * Updated dependencies 77 | * Added include support (for files in the same repository) 78 | 79 | See https://github.com/asciidoctor/gitbucket-asciidoctor-plugin/milestone/6?closed=1[list of closed issues and pull requests]. 80 | 81 | === gitbucket-asciidoctor-plugin 1.0.2 - 2017-03-08 82 | 83 | * Added support to provide attributes to the asciidoctor engine via properties file in gitbucket directory. 84 | 85 | === gitbucket-asciidoctor-plugin 1.0.1 - 2016-06-01 86 | 87 | * Post-process `src` attribute of generated `` tags to point to raw image resource. 88 | 89 | === gitbucket-asciidoctor-plugin 1.0.0 - 2016-05-03 90 | 91 | * Set the `outfilesuffix` attribute to `.adoc` to properly support xref's. 92 | * Introduced new attribute `gitbucket-branch` which contains the current selected git branch (or hash). 93 | * Requires GitBucket 4.0 or newer. 94 | 95 | === gitbucket-asciidoctor-plugin 0.1.1 - 2016-02-02 96 | 97 | * Updated some dependency versions. 98 | * Set the attributes `env=gitbucket` and `env-gitbucket=true` so that rendered pages can apply environment specific logic. 99 | 100 | === gitbucket-asciidoctor-plugin 0.1.0 - 2015-10-06 101 | 102 | * Initial release 103 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | name := "gitbucket-asciidoctor-plugin" 2 | organization := "com.github.lefou" 3 | version := "1.2.0" 4 | scalaVersion := "2.13.12" 5 | scalacOptions ++= Seq( 6 | "-deprecation", 7 | "-Xlint:unused" 8 | ) 9 | gitbucketVersion := "4.40.0" 10 | sourcesInBase := false 11 | 12 | resolvers ++= Seq( 13 | Resolver.jcenterRepo, 14 | Resolver.mavenLocal 15 | ) 16 | 17 | libraryDependencies ++= Seq( 18 | "javax.servlet" % "javax.servlet-api" % "3.1.0" % "provided", 19 | "org.asciidoctor" % "asciidoctorj" % "1.5.6", 20 | "net.sourceforge.htmlcleaner" % "htmlcleaner" % "2.21" 21 | ) 22 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.9.8 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("io.github.gitbucket" % "sbt-gitbucket-plugin" % "1.6.0") -------------------------------------------------------------------------------- /src/main/scala/Plugin.scala: -------------------------------------------------------------------------------- 1 | import scala.util.Try 2 | 3 | import org.slf4j.LoggerFactory 4 | 5 | import gitbucket.core.plugin.PluginRegistry 6 | import gitbucket.core.service.SystemSettingsService.SystemSettings 7 | import io.github.gitbucket.solidbase.model.Version 8 | import javax.servlet.ServletContext 9 | import tobiasroeser.gitbucket.asciidoctor.AsciidoctorRenderer 10 | 11 | class Plugin extends gitbucket.core.plugin.Plugin { 12 | 13 | private[this] val log = LoggerFactory.getLogger(classOf[Plugin]) 14 | 15 | override val pluginId: String = "asciidoctor" 16 | override val pluginName: String = "AsciiDoctor Plugin" 17 | override val description: String = "Provides AsciiDoc rendering for GitBucket." 18 | override val versions: List[Version] = List( 19 | new Version("1.0.1"), 20 | new Version("1.0.2"), 21 | new Version("1.1.0") 22 | ) 23 | 24 | private[this] var renderer: Option[AsciidoctorRenderer] = None 25 | 26 | override def initialize(registry: PluginRegistry, context: ServletContext, settings: SystemSettings): Unit = { 27 | 28 | log.info("About to initialize Asciidoctor") 29 | 30 | val test = Try { new AsciidoctorRenderer() } 31 | log.info("Result: " + test) 32 | val asciidoc = test.get 33 | 34 | log.info("Registering AsciidoctorRenderer for various extensions") 35 | registry.addRenderer("adoc", asciidoc) 36 | registry.addRenderer("asciidoc", asciidoc) 37 | registry.addRenderer("ad", asciidoc) 38 | 39 | renderer = Option(asciidoc) 40 | 41 | } 42 | 43 | override def shutdown(registry: PluginRegistry, context: ServletContext, settings: SystemSettings): Unit = { 44 | renderer.map(r => r.shutdown()) 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/scala/tobiasroeser/gitbucket/asciidoctor/AsciidoctorJgitIncludeProcessor.scala: -------------------------------------------------------------------------------- 1 | package tobiasroeser.gitbucket.asciidoctor 2 | 3 | import gitbucket.core.service.RepositoryService.RepositoryInfo 4 | import gitbucket.core.service.{AccountService, RepositoryService} 5 | import gitbucket.core.util.{Directory, JGitUtil, StringUtil} 6 | import org.asciidoctor.ast.DocumentRuby 7 | import org.asciidoctor.extension.{IncludeProcessor, PreprocessorReader} 8 | import org.eclipse.jgit.api.Git 9 | import org.slf4j.LoggerFactory 10 | 11 | import java.net.URI 12 | import java.util 13 | import scala.jdk.CollectionConverters._ 14 | import scala.util.Using 15 | 16 | class AsciidoctorJgitIncludeProcessor(config: java.util.Map[String, Object]) extends IncludeProcessor(config) 17 | with RepositoryService with AccountService{ 18 | val logger = LoggerFactory.getLogger(getClass) 19 | 20 | override def handles(target: String): Boolean = { 21 | true 22 | } 23 | 24 | override def process(document: DocumentRuby, reader: PreprocessorReader, target: String, attributes: util.Map[String, AnyRef]): Unit = { 25 | val documentPath = URI.create(document.getAttr("gitbucket-path").toString) 26 | val repository = document.getAttr("gitbucket-repository").asInstanceOf[RepositoryInfo] 27 | val branch = document.getAttr("gitbucket-branch").toString 28 | val targetPath = documentPath.resolve(target) 29 | 30 | Using.resource(Git.open(Directory.getRepositoryDir(repository.owner, repository.name))) { git => 31 | val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve(branch)) 32 | JGitUtil.getContentFromPath(git, revCommit.getTree, targetPath.toString, true).map{ bytes => 33 | val content = StringUtil.convertFromByteArray(bytes) 34 | val embed = if(attributes.asScala.contains("lines")){ 35 | val lines = attributes.get("lines").toString 36 | val linesRe = """(\d+)\.\.(\d+)""".r 37 | lines match { 38 | case linesRe(start, end) => 39 | content.split("""\r?\n""").slice(start.toInt - 1, end.toInt).mkString("\n") 40 | } 41 | }else{ 42 | content 43 | } 44 | reader.push_include(embed, target, target, 1, attributes) 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/scala/tobiasroeser/gitbucket/asciidoctor/AsciidoctorRenderer.scala: -------------------------------------------------------------------------------- 1 | package tobiasroeser.gitbucket.asciidoctor 2 | 3 | import org.asciidoctor.Asciidoctor 4 | import org.asciidoctor.AttributesBuilder 5 | import org.asciidoctor.OptionsBuilder 6 | import org.asciidoctor.SafeMode 7 | import org.htmlcleaner.HtmlCleaner 8 | import org.htmlcleaner.HtmlNode 9 | import org.htmlcleaner.SimpleHtmlSerializer 10 | import org.htmlcleaner.TagNode 11 | import org.htmlcleaner.TagNodeVisitor 12 | import org.slf4j.LoggerFactory 13 | import java.util.Properties 14 | import java.io.File 15 | import scala.jdk.CollectionConverters._ 16 | 17 | import gitbucket.core.controller.Context 18 | import gitbucket.core.plugin.RenderRequest 19 | import gitbucket.core.plugin.Renderer 20 | import gitbucket.core.service.RepositoryService.RepositoryInfo 21 | import gitbucket.core.view.helpers 22 | import gitbucket.core.util.Directory.GitBucketHome 23 | import play.twirl.api.Html 24 | 25 | class AsciidoctorRenderer extends Renderer { 26 | 27 | private[this] val log = LoggerFactory.getLogger(classOf[AsciidoctorRenderer]) 28 | 29 | private[this] var _asciidoctor: Option[Asciidoctor] = None 30 | 31 | private[this] def asciidoctor: Asciidoctor = _asciidoctor match { 32 | case None => 33 | log.info("About to create Asciidoctor") 34 | _asciidoctor = Option(Asciidoctor.Factory.create(getClass().getClassLoader())) 35 | _asciidoctor.get.javaExtensionRegistry().includeProcessor(classOf[AsciidoctorJgitIncludeProcessor]) 36 | _asciidoctor.get 37 | case Some(a) => a 38 | } 39 | 40 | def shutdown(): Unit = { 41 | _asciidoctor.map(_.shutdown()) 42 | } 43 | 44 | def render(request: RenderRequest): Html = { 45 | import request._ 46 | Html(toHtml(filePath, fileContent, branch, repository, enableWikiLink, enableRefsLink)(context)) 47 | } 48 | 49 | def toHtml(filePath: List[String], asciidoc: String, branch: String, repository: RepositoryInfo, 50 | enableWikiLink: Boolean, enableRefsLink: Boolean)(implicit context: Context): String = { 51 | 52 | log.info("About to render Asciidoctor") 53 | 54 | val options = OptionsBuilder.options() 55 | options.safe(SafeMode.SECURE) 56 | val attributes = AttributesBuilder.attributes() 57 | attributes.showTitle(true) 58 | attributes.attribute("env", "gitbucket") 59 | attributes.attribute("env-gitbucket", true) 60 | attributes.attribute("outfilesuffix", ".adoc") 61 | attributes.attribute("gitbucket-branch", branch) 62 | attributes.attribute("gitbucket-repository", repository) 63 | attributes.attribute("gitbucket-path", filePath.mkString("/")) 64 | 65 | val asciidocAttributes = new File(GitBucketHome, "/asciidoctor.properties") 66 | val propsJava = new Properties(); 67 | if(asciidocAttributes.exists){ 68 | val in = new java.io.FileInputStream(asciidocAttributes) 69 | propsJava.load(in) 70 | in.close() 71 | } 72 | 73 | val props = propsJava.stringPropertyNames().asScala 74 | props.foreach(k => { 75 | attributes.attribute(k, propsJava.getProperty(k)) 76 | }) 77 | 78 | options.attributes(attributes.get()) 79 | val rendered = asciidoctor.render(asciidoc, options) 80 | 81 | val path = filePath.reverse.tail.reverse match { 82 | case Nil => "" 83 | case p => p.mkString("", "/", "/") 84 | } 85 | val relativeUrlPrefix = s"${helpers.url(repository)}/blob/${branch}/${path}" 86 | val relativeImageUrlPrefix = s"${helpers.url(repository)}/raw/${branch}/${path}" 87 | prefixRelativeUrls(rendered, relativeUrlPrefix, relativeImageUrlPrefix) 88 | } 89 | 90 | private[this] val exceptionPrefixes = Seq("#", "/", "http://", "https://") 91 | 92 | def prefixRelativeUrls(html: String, urlPrefix: String, imageUrlPrefix: String): String = { 93 | val cleaner = new HtmlCleaner() 94 | val node = cleaner.clean(html) 95 | node.traverse(new TagNodeVisitor() { 96 | override def visit(tagNode: TagNode, htmlNode: HtmlNode): Boolean = { 97 | htmlNode match { 98 | case tag: TagNode if tag.getName == "a" => 99 | Option(tag.getAttributeByName("href")) foreach { href => 100 | if (exceptionPrefixes.forall(p => !href.startsWith(p))) { 101 | tag.addAttribute("href", s"${urlPrefix}${href}") 102 | } 103 | } 104 | case tag: TagNode if tag.getName == "img" => 105 | Option(tag.getAttributeByName("src")) foreach { src => 106 | if (exceptionPrefixes.forall(p => !src.startsWith(p))) { 107 | tag.addAttribute("src", s"${imageUrlPrefix}${src}") 108 | } 109 | } 110 | case _ => 111 | } 112 | // continue traversal 113 | true 114 | } 115 | }) 116 | new SimpleHtmlSerializer(cleaner.getProperties()).getAsString(node) 117 | } 118 | } --------------------------------------------------------------------------------