|
| 1 | +package tobiasroeser.gitbucket.asciidoctor |
| 2 | + |
| 3 | +import java.io.File |
| 4 | +import java.net.URI |
| 5 | +import java.util |
| 6 | + |
| 7 | +import gitbucket.core.service.{AccountService, RepositoryService} |
| 8 | +import gitbucket.core.service.RepositoryService.RepositoryInfo |
| 9 | +import gitbucket.core.util.{JGitUtil, StringUtil} |
| 10 | +import gitbucket.core.util.Directory._ |
| 11 | +import gitbucket.core.util.SyntaxSugars._ |
| 12 | +import org.asciidoctor.ast.DocumentRuby |
| 13 | +import org.asciidoctor.extension.{IncludeProcessor, PreprocessorReader} |
| 14 | +import org.eclipse.jgit.api.Git |
| 15 | +import org.slf4j.LoggerFactory |
| 16 | + |
| 17 | +import scala.collection.JavaConverters._ |
| 18 | + |
| 19 | +class AsciidoctorJgitIncludeProcessor(config: java.util.Map[String, Object]) extends IncludeProcessor(config) |
| 20 | + with RepositoryService with AccountService{ |
| 21 | + val logger = LoggerFactory.getLogger(getClass) |
| 22 | + |
| 23 | + override def handles(target: String): Boolean = { |
| 24 | + true |
| 25 | + } |
| 26 | + |
| 27 | + override def process(document: DocumentRuby, reader: PreprocessorReader, target: String, attributes: util.Map[String, AnyRef]): Unit = { |
| 28 | + val documentPath = URI.create(document.getAttr("gitbucket-path").toString) |
| 29 | + val repository = document.getAttr("gitbucket-repository").asInstanceOf[RepositoryInfo] |
| 30 | + val branch = document.getAttr("gitbucket-branch").toString |
| 31 | + val targetPath = documentPath.resolve(target) |
| 32 | + |
| 33 | + using(Git.open(getRepositoryDir(repository.owner, repository.name))) { git => |
| 34 | + val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve(branch)) |
| 35 | + JGitUtil.getContentFromPath(git, revCommit.getTree, targetPath.toString, true).map{ bytes => |
| 36 | + val content = StringUtil.convertFromByteArray(bytes) |
| 37 | + val embed = if(attributes.asScala.contains("lines")){ |
| 38 | + val lines = attributes.get("lines").toString |
| 39 | + val linesRe = """(\d+)\.\.(\d+)""".r |
| 40 | + lines match { |
| 41 | + case linesRe(start, end) => |
| 42 | + content.split("""\r?\n""").slice(start.toInt - 1, end.toInt).mkString("\n") |
| 43 | + } |
| 44 | + }else{ |
| 45 | + content |
| 46 | + } |
| 47 | + reader.push_include(embed, target, target, 1, attributes) |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | +} |
0 commit comments