diff --git a/.gitignore b/.gitignore index c7edac1..8f97d68 100644 --- a/.gitignore +++ b/.gitignore @@ -1,83 +1,105 @@ # Compiled Object files *.slo *.lo *.o *.obj # Compiled Dynamic libraries *.so *.so.* *.dylib *.dll # Compiled Static libraries *.lai *.la *.a *.lib # Executables *.exe *.out *.app *.class # Mobile Tools for Java (J2ME) .mtj.tmp/ # Package Files # *.jar *.war *.ear # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* # Qt-es /.qmake.cache /.qmake.stash *.pro.user *.pro.user.* *.moc moc_*.cpp qrc_*.cpp ui_*.h Makefile* *-build-* # QtCreator *.autosave coco/*.old coco/*~ *~ + # XREATE -cpp/build-*/* + +cpp/build-*/ cpp/xreate-debug/* cpp/xreate-release/* cpp/.idea CMakeLists.txt.user cmake_install.cmake project/* nb*.xml .* target/* /tools/phabricator/xreate-frontend/nbproject/private/ documentation/trash4/ trash/ CMakeFiles/ gen-cpp/ generated-cpp/ gen-php/ generated-js/ books/ build/ coco/Parser.* coco/Scanner.* - tools/phabricator/administration/ -**/tmp-* +tmp-* cpp/tests/vendorsAPI/ +secrets/ +/tools/site/init-data/ +code-coverage.sh +codestyle-netbeans/ +deferred/ +design/ +documentation-tools/xmlmind-custom-css +grammar/main/ +grammar/modules/ +model-to-graph +tools/netdata* +tools/nginx-tests/ +tools/phabricator/diagrams/ +tools/phabricator/docker/ +tools/phabricator/nbproject/ +tools/phabricator/xreate-frontend/install-xreate-frontend.sh +tools/scaleway-perf +tools/scaleway-perf.ods +tools/site/init-data/ +tools/site/secrets/ +valgrind.sh diff --git a/documentation-api/doxygenctl b/documentation-api/doxygenctl index 6a988d1..023afe7 100755 --- a/documentation-api/doxygenctl +++ b/documentation-api/doxygenctl @@ -1,20 +1,20 @@ #!/bin/bash SCRIPT=`realpath $0` DIR=`dirname $SCRIPT` generate () { echo ${DIR} cd ${DIR} doxygen ./XreateDoxyfile } transfer() { - scp -P24 -r ${DIR}/tmp-generated-doc-api/html/ xreate@xreate.org:/opt/xreate-documentation-api/ + rsync -rtvzl -e 'ssh -p 24' ${DIR}/tmp-generated-doc-api/html/ xreate@$1:$2/ } case $1 in local) generate ;; - remote) generate && transfer ;; - *) echo "usage: local | remote ";; + remote) generate && transfer $2 $3;; + *) echo "usage: local | remote ";; esac diff --git a/documentation-tools/doc-converter/DocBook.hs b/documentation-tools/doc-converter/DocBook.hs index e4bd766..8ea2560 100644 --- a/documentation-tools/doc-converter/DocBook.hs +++ b/documentation-tools/doc-converter/DocBook.hs @@ -1,1133 +1,1141 @@ {-# LANGUAGE NoImplicitPrelude #-} -{- -Copyright (C) 2006-2018 John MacFarlane - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA --} - +{-# LANGUAGE OverloadedStrings #-} {- | Module : Text.Pandoc.Readers.DocBook - Copyright : Copyright (C) 2006-2018 John MacFarlane + Copyright : Copyright (C) 2006-2019 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane Stability : alpha Portability : portable Conversion of DocBook XML to 'Pandoc' document. -} module Text.Pandoc.Readers.DocBook ( readDocBook ) where import Prelude import Control.Monad.State.Strict import Data.Char (isSpace, toUpper) import Data.Default import Data.Either (rights) import Data.Foldable (asum) import Data.Generics import Data.List (intersperse) import Data.Maybe (fromMaybe) import Data.Text (Text) import qualified Data.Text as T import Text.HTML.TagSoup.Entity (lookupEntity) import Text.Pandoc.Builder -import Text.Pandoc.Class (PandocMonad) +import Text.Pandoc.Class (PandocMonad, report) import Text.Pandoc.Options +import Text.Pandoc.Logging (LogMessage(..)) import Text.Pandoc.Shared (crFilter, safeRead) import Text.TeXMath (readMathML, writeTeX) import Text.XML.Light {- List of all DocBook tags, with [x] indicating implemented, [o] meaning intentionally left unimplemented (pass through): [o] abbrev - An abbreviation, especially one followed by a period [x] abstract - A summary [o] accel - A graphical user interface (GUI) keyboard shortcut [x] ackno - Acknowledgements in an Article [o] acronym - An often pronounceable word made from the initial [o] action - A response to a user event [o] address - A real-world address, generally a postal address [ ] affiliation - The institutional affiliation of an individual [ ] alt - Text representation for a graphical element [o] anchor - A spot in the document [x] answer - An answer to a question posed in a QandASet [x] appendix - An appendix in a Book or Article [x] appendixinfo - Meta-information for an Appendix [o] application - The name of a software program [x] area - A region defined for a Callout in a graphic or code example [x] areaset - A set of related areas in a graphic or code example [x] areaspec - A collection of regions in a graphic or code example [ ] arg - An argument in a CmdSynopsis [x] article - An article [x] articleinfo - Meta-information for an Article [ ] artpagenums - The page numbers of an article as published [x] attribution - The source of a block quote or epigraph [ ] audiodata - Pointer to external audio data [ ] audioobject - A wrapper for audio data and its associated meta-information [x] author - The name of an individual author [ ] authorblurb - A short description or note about an author [x] authorgroup - Wrapper for author information when a document has multiple authors or collaborators [x] authorinitials - The initials or other short identifier for an author [o] beginpage - The location of a page break in a print version of the document [ ] bibliocoverage - The spatial or temporal coverage of a document [x] bibliodiv - A section of a Bibliography [x] biblioentry - An entry in a Bibliography [x] bibliography - A bibliography [ ] bibliographyinfo - Meta-information for a Bibliography [ ] biblioid - An identifier for a document [o] bibliolist - A wrapper for a set of bibliography entries [ ] bibliomisc - Untyped bibliographic information [x] bibliomixed - An entry in a Bibliography [ ] bibliomset - A cooked container for related bibliographic information [ ] biblioref - A cross reference to a bibliographic entry [ ] bibliorelation - The relationship of a document to another [ ] biblioset - A raw container for related bibliographic information [ ] bibliosource - The source of a document [ ] blockinfo - Meta-information for a block element [x] blockquote - A quotation set off from the main text [x] book - A book [x] bookinfo - Meta-information for a Book [x] bridgehead - A free-floating heading [x] callout - A “called out” description of a marked Area [x] calloutlist - A list of Callouts [x] caption - A caption [x] caution - A note of caution [x] chapter - A chapter, as of a book [x] chapterinfo - Meta-information for a Chapter [ ] citation - An inline bibliographic reference to another published work [ ] citebiblioid - A citation of a bibliographic identifier [ ] citerefentry - A citation to a reference page [ ] citetitle - The title of a cited work [ ] city - The name of a city in an address [x] classname - The name of a class, in the object-oriented programming sense [ ] classsynopsis - The syntax summary for a class definition [ ] classsynopsisinfo - Information supplementing the contents of a ClassSynopsis [ ] cmdsynopsis - A syntax summary for a software command [ ] co - The location of a callout embedded in text [x] code - An inline code fragment [x] col - Specifications for a column in an HTML table [x] colgroup - A group of columns in an HTML table [ ] collab - Identifies a collaborator [ ] collabname - The name of a collaborator [ ] colophon - Text at the back of a book describing facts about its production [x] colspec - Specifications for a column in a table [x] command - The name of an executable program or other software command [x] computeroutput - Data, generally text, displayed or presented by a computer [ ] confdates - The dates of a conference for which a document was written [ ] confgroup - A wrapper for document meta-information about a conference [ ] confnum - An identifier, frequently numerical, associated with a conference for which a document was written [ ] confsponsor - The sponsor of a conference for which a document was written [ ] conftitle - The title of a conference for which a document was written [x] constant - A programming or system constant [ ] constraint - A constraint in an EBNF production [ ] constraintdef - The definition of a constraint in an EBNF production [ ] constructorsynopsis - A syntax summary for a constructor [ ] contractnum - The contract number of a document [ ] contractsponsor - The sponsor of a contract [ ] contrib - A summary of the contributions made to a document by a credited source [ ] copyright - Copyright information about a document [ ] coref - A cross reference to a co [ ] corpauthor - A corporate author, as opposed to an individual [ ] corpcredit - A corporation or organization credited in a document [ ] corpname - The name of a corporation [ ] country - The name of a country [ ] database - The name of a database, or part of a database [x] date - The date of publication or revision of a document [ ] dedication - A wrapper for the dedication section of a book [ ] destructorsynopsis - A syntax summary for a destructor [ ] edition - The name or number of an edition of a document [ ] editor - The name of the editor of a document [x] email - An email address [x] emphasis - Emphasized text [x] entry - A cell in a table [ ] entrytbl - A subtable appearing in place of an Entry in a table [ ] envar - A software environment variable [x] epigraph - A short inscription at the beginning of a document or component note: also handle embedded attribution tag [x] equation - A displayed mathematical equation [ ] errorcode - An error code [ ] errorname - An error name [ ] errortext - An error message. [ ] errortype - The classification of an error message [ ] example - A formal example, with a title [ ] exceptionname - The name of an exception [ ] fax - A fax number [ ] fieldsynopsis - The name of a field in a class definition [x] figure - A formal figure, generally an illustration, with a title [x] filename - The name of a file [ ] firstname - The first name of a person [ ] firstterm - The first occurrence of a term [x] footnote - A footnote [ ] footnoteref - A cross reference to a footnote (a footnote mark) [x] foreignphrase - A word or phrase in a language other than the primary language of the document [x] formalpara - A paragraph with a title [ ] funcdef - A function (subroutine) name and its return type [ ] funcparams - Parameters for a function referenced through a function pointer in a synopsis [ ] funcprototype - The prototype of a function [ ] funcsynopsis - The syntax summary for a function definition [ ] funcsynopsisinfo - Information supplementing the FuncDefs of a FuncSynopsis [x] function - The name of a function or subroutine, as in a programming language [x] glossary - A glossary [x] glossaryinfo - Meta-information for a Glossary [x] glossdef - A definition in a GlossEntry [x] glossdiv - A division in a Glossary [x] glossentry - An entry in a Glossary or GlossList [x] glosslist - A wrapper for a set of GlossEntrys [x] glosssee - A cross-reference from one GlossEntry to another [x] glossseealso - A cross-reference from one GlossEntry to another [x] glossterm - A glossary term [ ] graphic - A displayed graphical object (not an inline) Note: in DocBook v5 `graphic` is discarded [ ] graphicco - A graphic that contains callout areas Note: in DocBook v5 `graphicco` is discarded [ ] group - A group of elements in a CmdSynopsis [ ] guibutton - The text on a button in a GUI [ ] guiicon - Graphic and/or text appearing as a icon in a GUI [ ] guilabel - The text of a label in a GUI [x] guimenu - The name of a menu in a GUI [x] guimenuitem - The name of a terminal menu item in a GUI [x] guisubmenu - The name of a submenu in a GUI [ ] hardware - A physical part of a computer system [ ] highlights - A summary of the main points of the discussed component [ ] holder - The name of the individual or organization that holds a copyright [o] honorific - The title of a person [ ] html:form - An HTML form [x] imagedata - Pointer to external image data (only `fileref` attribute implemented but not `entityref` which would require parsing of the DTD) [x] imageobject - A wrapper for image data and its associated meta-information [ ] imageobjectco - A wrapper for an image object with callouts [x] important - An admonition set off from the text [x] index - An index [x] indexdiv - A division in an index [x] indexentry - An entry in an index [x] indexinfo - Meta-information for an Index [x] indexterm - A wrapper for terms to be indexed [x] info - A wrapper for information about a component or other block. (DocBook v5) [x] informalequation - A displayed mathematical equation without a title [x] informalexample - A displayed example without a title [ ] informalfigure - A untitled figure [ ] informaltable - A table without a title [ ] initializer - The initializer for a FieldSynopsis [x] inlineequation - A mathematical equation or expression occurring inline [ ] inlinegraphic - An object containing or pointing to graphical data that will be rendered inline [x] inlinemediaobject - An inline media object (video, audio, image, and so on) [ ] interface - An element of a GUI [ ] interfacename - The name of an interface [ ] invpartnumber - An inventory part number [ ] isbn - The International Standard Book Number of a document [ ] issn - The International Standard Serial Number of a periodical [ ] issuenum - The number of an issue of a journal [x] itemizedlist - A list in which each entry is marked with a bullet or other dingbat [ ] itermset - A set of index terms in the meta-information of a document [ ] jobtitle - The title of an individual in an organization [x] keycap - The text printed on a key on a keyboard [ ] keycode - The internal, frequently numeric, identifier for a key on a keyboard [x] keycombo - A combination of input actions [ ] keysym - The symbolic name of a key on a keyboard [ ] keyword - One of a set of keywords describing the content of a document [ ] keywordset - A set of keywords describing the content of a document [ ] label - A label on a Question or Answer [ ] legalnotice - A statement of legal obligations or requirements [ ] lhs - The left-hand side of an EBNF production [ ] lineage - The portion of a person's name indicating a relationship to ancestors [ ] lineannotation - A comment on a line in a verbatim listing [x] link - A hypertext link [x] listitem - A wrapper for the elements of a list item [x] literal - Inline text that is some literal value [x] literallayout - A block of text in which line breaks and white space are to be reproduced faithfully [ ] lot - A list of the titles of formal objects (as tables or figures) in a document [ ] lotentry - An entry in a list of titles [ ] manvolnum - A reference volume number [x] markup - A string of formatting markup in text that is to be represented literally [x] mathphrase - A mathematical phrase, an expression that can be represented with ordinary text and a small amount of markup [ ] medialabel - A name that identifies the physical medium on which some information resides [x] mediaobject - A displayed media object (video, audio, image, etc.) [ ] mediaobjectco - A media object that contains callouts [x] member - An element of a simple list [x] menuchoice - A selection or series of selections from a menu [ ] methodname - The name of a method [ ] methodparam - Parameters to a method [ ] methodsynopsis - A syntax summary for a method [x] mml:math - A MathML equation [ ] modespec - Application-specific information necessary for the completion of an OLink [ ] modifier - Modifiers in a synopsis [ ] mousebutton - The conventional name of a mouse button [ ] msg - A message in a message set [ ] msgaud - The audience to which a message in a message set is relevant [ ] msgentry - A wrapper for an entry in a message set [ ] msgexplan - Explanatory material relating to a message in a message set [ ] msginfo - Information about a message in a message set [ ] msglevel - The level of importance or severity of a message in a message set [ ] msgmain - The primary component of a message in a message set [ ] msgorig - The origin of a message in a message set [ ] msgrel - A related component of a message in a message set [ ] msgset - A detailed set of messages, usually error messages [ ] msgsub - A subcomponent of a message in a message set [ ] msgtext - The actual text of a message component in a message set [ ] nonterminal - A non-terminal in an EBNF production [x] note - A message set off from the text [ ] objectinfo - Meta-information for an object [ ] olink - A link that addresses its target indirectly, through an entity [ ] ooclass - A class in an object-oriented programming language [ ] ooexception - An exception in an object-oriented programming language [ ] oointerface - An interface in an object-oriented programming language [x] option - An option for a software command [x] optional - Optional information [x] orderedlist - A list in which each entry is marked with a sequentially incremented label [ ] orgdiv - A division of an organization [ ] orgname - The name of an organization other than a corporation [ ] otheraddr - Uncategorized information in address [ ] othercredit - A person or entity, other than an author or editor, credited in a document [ ] othername - A component of a persons name that is not a first name, surname, or lineage [ ] package - A package [ ] pagenums - The numbers of the pages in a book, for use in a bibliographic entry [x] para - A paragraph [ ] paramdef - Information about a function parameter in a programming language [x] parameter - A value or a symbolic reference to a value [ ] part - A division in a book [ ] partinfo - Meta-information for a Part [ ] partintro - An introduction to the contents of a part [ ] personblurb - A short description or note about a person [ ] personname - The personal name of an individual [ ] phone - A telephone number [ ] phrase - A span of text [ ] pob - A post office box in an address [ ] postcode - A postal code in an address [x] preface - Introductory matter preceding the first chapter of a book [ ] prefaceinfo - Meta-information for a Preface [ ] primary - The primary word or phrase under which an index term should be sorted [ ] primaryie - A primary term in an index entry, not in the text [ ] printhistory - The printing history of a document [ ] procedure - A list of operations to be performed in a well-defined sequence [ ] production - A production in a set of EBNF productions [ ] productionrecap - A cross-reference to an EBNF production [ ] productionset - A set of EBNF productions [ ] productname - The formal name of a product [ ] productnumber - A number assigned to a product [x] programlisting - A literal listing of all or part of a program [ ] programlistingco - A program listing with associated areas used in callouts [x] prompt - A character or string indicating the start of an input field in a computer display [ ] property - A unit of data associated with some part of a computer system [ ] pubdate - The date of publication of a document [ ] publisher - The publisher of a document [ ] publishername - The name of the publisher of a document [ ] pubsnumber - A number assigned to a publication other than an ISBN or ISSN or inventory part number [x] qandadiv - A titled division in a QandASet [o] qandaentry - A question/answer set within a QandASet [o] qandaset - A question-and-answer set [x] question - A question in a QandASet [x] quote - An inline quotation [ ] refclass - The scope or other indication of applicability of a reference entry [ ] refdescriptor - A description of the topic of a reference page [ ] refentry - A reference page (originally a UNIX man-style reference page) [ ] refentryinfo - Meta-information for a Refentry [ ] refentrytitle - The title of a reference page [ ] reference - A collection of reference entries [ ] referenceinfo - Meta-information for a Reference [ ] refmeta - Meta-information for a reference entry [ ] refmiscinfo - Meta-information for a reference entry other than the title and volume number [ ] refname - The name of (one of) the subject(s) of a reference page [ ] refnamediv - The name, purpose, and classification of a reference page [ ] refpurpose - A short (one sentence) synopsis of the topic of a reference page [x] refsect1 - A major subsection of a reference entry [x] refsect1info - Meta-information for a RefSect1 [x] refsect2 - A subsection of a RefSect1 [x] refsect2info - Meta-information for a RefSect2 [x] refsect3 - A subsection of a RefSect2 [x] refsect3info - Meta-information for a RefSect3 [x] refsection - A recursive section in a refentry [x] refsectioninfo - Meta-information for a refsection [ ] refsynopsisdiv - A syntactic synopsis of the subject of the reference page [ ] refsynopsisdivinfo - Meta-information for a RefSynopsisDiv [x] releaseinfo - Information about a particular release of a document [ ] remark - A remark (or comment) intended for presentation in a draft manuscript [ ] replaceable - Content that may or must be replaced by the user [ ] returnvalue - The value returned by a function [ ] revdescription - A extended description of a revision to a document [ ] revhistory - A history of the revisions to a document [ ] revision - An entry describing a single revision in the history of the revisions to a document [ ] revnumber - A document revision number [ ] revremark - A description of a revision to a document [ ] rhs - The right-hand side of an EBNF production [x] row - A row in a table [ ] sbr - An explicit line break in a command synopsis [x] screen - Text that a user sees or might see on a computer screen [o] screenco - A screen with associated areas used in callouts [o] screeninfo - Information about how a screen shot was produced [ ] screenshot - A representation of what the user sees or might see on a computer screen [ ] secondary - A secondary word or phrase in an index term [ ] secondaryie - A secondary term in an index entry, rather than in the text [x] sect1 - A top-level section of document [x] sect1info - Meta-information for a Sect1 [x] sect2 - A subsection within a Sect1 [x] sect2info - Meta-information for a Sect2 [x] sect3 - A subsection within a Sect2 [x] sect3info - Meta-information for a Sect3 [x] sect4 - A subsection within a Sect3 [x] sect4info - Meta-information for a Sect4 [x] sect5 - A subsection within a Sect4 [x] sect5info - Meta-information for a Sect5 [x] section - A recursive section [x] sectioninfo - Meta-information for a recursive section [x] see - Part of an index term directing the reader instead to another entry in the index [x] seealso - Part of an index term directing the reader also to another entry in the index [ ] seealsoie - A See also entry in an index, rather than in the text [ ] seeie - A See entry in an index, rather than in the text [x] seg - An element of a list item in a segmented list [x] seglistitem - A list item in a segmented list [x] segmentedlist - A segmented list, a list of sets of elements [x] segtitle - The title of an element of a list item in a segmented list [ ] seriesvolnums - Numbers of the volumes in a series of books [ ] set - A collection of books [ ] setindex - An index to a set of books [ ] setindexinfo - Meta-information for a SetIndex [ ] setinfo - Meta-information for a Set [ ] sgmltag - A component of SGML markup [ ] shortaffil - A brief description of an affiliation [ ] shortcut - A key combination for an action that is also accessible through a menu [ ] sidebar - A portion of a document that is isolated from the main narrative flow [ ] sidebarinfo - Meta-information for a Sidebar [x] simpara - A paragraph that contains only text and inline markup, no block elements [x] simplelist - An undecorated list of single words or short phrases [ ] simplemsgentry - A wrapper for a simpler entry in a message set [ ] simplesect - A section of a document with no subdivisions [ ] spanspec - Formatting information for a spanned column in a table [ ] state - A state or province in an address [ ] step - A unit of action in a procedure [ ] stepalternatives - Alternative steps in a procedure [ ] street - A street address in an address [ ] structfield - A field in a structure (in the programming language sense) [ ] structname - The name of a structure (in the programming language sense) [ ] subject - One of a group of terms describing the subject matter of a document [ ] subjectset - A set of terms describing the subject matter of a document [ ] subjectterm - A term in a group of terms describing the subject matter of a document [x] subscript - A subscript (as in H2O, the molecular formula for water) [ ] substeps - A wrapper for steps that occur within steps in a procedure [x] subtitle - The subtitle of a document [x] superscript - A superscript (as in x2, the mathematical notation for x multiplied by itself) [ ] surname - A family name; in western cultures the last name [ ] svg:svg - An SVG graphic [x] symbol - A name that is replaced by a value before processing [ ] synopfragment - A portion of a CmdSynopsis broken out from the main body of the synopsis [ ] synopfragmentref - A reference to a fragment of a command synopsis [ ] synopsis - A general-purpose element for representing the syntax of commands or functions [ ] systemitem - A system-related item or term [ ] table - A formal table in a document [ ] task - A task to be completed [ ] taskprerequisites - The prerequisites for a task [ ] taskrelated - Information related to a task [ ] tasksummary - A summary of a task [x] tbody - A wrapper for the rows of a table or informal table [x] td - A table entry in an HTML table [x] term - The word or phrase being defined or described in a variable list [ ] termdef - An inline term definition [ ] tertiary - A tertiary word or phrase in an index term [ ] tertiaryie - A tertiary term in an index entry, rather than in the text [ ] textdata - Pointer to external text data [ ] textobject - A wrapper for a text description of an object and its associated meta-information [ ] tfoot - A table footer consisting of one or more rows [x] tgroup - A wrapper for the main content of a table, or part of a table [x] th - A table header entry in an HTML table [x] thead - A table header consisting of one or more rows [x] tip - A suggestion to the user, set off from the text [x] title - The text of the title of a section of a document or of a formal block-level element [x] titleabbrev - The abbreviation of a Title [x] toc - A table of contents [x] tocback - An entry in a table of contents for a back matter component [x] tocchap - An entry in a table of contents for a component in the body of a document [x] tocentry - A component title in a table of contents [x] tocfront - An entry in a table of contents for a front matter component [x] toclevel1 - A top-level entry within a table of contents entry for a chapter-like component [x] toclevel2 - A second-level entry within a table of contents entry for a chapter-like component [x] toclevel3 - A third-level entry within a table of contents entry for a chapter-like component [x] toclevel4 - A fourth-level entry within a table of contents entry for a chapter-like component [x] toclevel5 - A fifth-level entry within a table of contents entry for a chapter-like component [x] tocpart - An entry in a table of contents for a part of a book [ ] token - A unit of information [x] tr - A row in an HTML table [ ] trademark - A trademark [x] type - The classification of a value [x] ulink - A link that addresses its target by means of a URL (Uniform Resource Locator) [x] uri - A Uniform Resource Identifier [x] userinput - Data entered by the user [x] varargs - An empty element in a function synopsis indicating a variable number of arguments [x] variablelist - A list in which each entry is composed of a set of one or more terms and an associated description [x] varlistentry - A wrapper for a set of terms and the associated description in a variable list [x] varname - The name of a variable [ ] videodata - Pointer to external video data [ ] videoobject - A wrapper for video data and its associated meta-information [ ] void - An empty element in a function synopsis indicating that the function in question takes no arguments [ ] volumenum - The volume number of a document in a set (as of books in a set or articles in a journal) [x] warning - An admonition set off from the text [x] wordasword - A word meant specifically as a word and not representing anything else [x] xref - A cross reference to another part of the document [ ] year - The year of publication of a document [x] ?asciidoc-br? - line break from asciidoc docbook output -} type DB m = StateT DBState m data DBState = DBState{ dbSectionLevel :: Int , dbQuoteType :: QuoteType , dbMeta :: Meta , dbBook :: Bool , dbFigureTitle :: Inlines , dbContent :: [Content] } deriving Show instance Default DBState where def = DBState{ dbSectionLevel = 0 , dbQuoteType = DoubleQuote , dbMeta = mempty , dbBook = False , dbFigureTitle = mempty , dbContent = [] } readDocBook :: PandocMonad m => ReaderOptions -> Text -> m Pandoc readDocBook _ inp = do - let tree = normalizeTree . parseXML . handleInstructions - $ T.unpack $ crFilter inp + let tree = normalizeTree . parseXML . handleInstructions $ crFilter inp (bs, st') <- flip runStateT (def{ dbContent = tree }) $ mapM parseBlock tree return $ Pandoc (dbMeta st') (toList . mconcat $ bs) -- We treat specially (issue #1236), converting it -- to
, since xml-light doesn't parse the instruction correctly. -- Other xml instructions are simply removed from the input stream. -handleInstructions :: String -> String -handleInstructions ('<':'?':'a':'s':'c':'i':'i':'d':'o':'c':'-':'b':'r':'?':'>':xs) = '<':'b':'r':'/':'>': handleInstructions xs -handleInstructions xs = case break (=='<') xs of +handleInstructions :: Text -> Text +handleInstructions = T.pack . handleInstructions' . T.unpack + +handleInstructions' :: String -> String +handleInstructions' ('<':'?':'a':'s':'c':'i':'i':'d':'o':'c':'-':'b':'r':'?':'>':xs) = '<':'b':'r':'/':'>': handleInstructions' xs +handleInstructions' xs = case break (=='<') xs of (ys, []) -> ys - ([], '<':zs) -> '<' : handleInstructions zs - (ys, zs) -> ys ++ handleInstructions zs + ([], '<':zs) -> '<' : handleInstructions' zs + (ys, zs) -> ys ++ handleInstructions' zs getFigure :: PandocMonad m => Element -> DB m Blocks getFigure e = do tit <- case filterChild (named "title") e of Just t -> getInlines t Nothing -> return mempty modify $ \st -> st{ dbFigureTitle = tit } res <- getBlocks e modify $ \st -> st{ dbFigureTitle = mempty } return res -- normalize input, consolidating adjacent Text and CRef elements normalizeTree :: [Content] -> [Content] normalizeTree = everywhere (mkT go) where go :: [Content] -> [Content] go (Text (CData CDataRaw _ _):xs) = xs go (Text (CData CDataText s1 z):Text (CData CDataText s2 _):xs) = Text (CData CDataText (s1 ++ s2) z):xs go (Text (CData CDataText s1 z):CRef r:xs) = Text (CData CDataText (s1 ++ convertEntity r) z):xs go (CRef r:Text (CData CDataText s1 z):xs) = Text (CData CDataText (convertEntity r ++ s1) z):xs go (CRef r1:CRef r2:xs) = Text (CData CDataText (convertEntity r1 ++ convertEntity r2) Nothing):xs go xs = xs convertEntity :: String -> String convertEntity e = Data.Maybe.fromMaybe (map toUpper e) (lookupEntity e) -- convenience function to get an attribute value, defaulting to "" -attrValue :: String -> Element -> String +attrValue :: String -> Element -> Text attrValue attr elt = - fromMaybe "" (lookupAttrBy (\x -> qName x == attr) (elAttribs elt)) + maybe "" T.pack (lookupAttrBy (\x -> qName x == attr) (elAttribs elt)) -- convenience function -named :: String -> Element -> Bool -named s e = qName (elName e) == s +named :: Text -> Element -> Bool +named s e = qName (elName e) == T.unpack s -- addMetadataFromElement :: PandocMonad m => Element -> DB m Blocks addMetadataFromElement e = do case filterChild (named "title") e of Nothing -> return () Just z -> do getInlines z >>= addMeta "title" addMetaField "subtitle" z case filterChild (named "authorgroup") e of Nothing -> return () Just z -> addMetaField "author" z addMetaField "subtitle" e addMetaField "author" e addMetaField "date" e addMetaField "release" e return mempty where addMetaField fieldname elt = case filterChildren (named fieldname) elt of [] -> return () [z] -> getInlines z >>= addMeta fieldname zs -> mapM getInlines zs >>= addMeta fieldname -addMeta :: PandocMonad m => ToMetaValue a => String -> a -> DB m () +addMeta :: PandocMonad m => ToMetaValue a => Text -> a -> DB m () addMeta field val = modify (setMeta field val) instance HasMeta DBState where setMeta field v s = s {dbMeta = setMeta field v (dbMeta s)} deleteMeta field s = s {dbMeta = deleteMeta field (dbMeta s)} isBlockElement :: Content -> Bool -isBlockElement (Elem e) = qName (elName e) `elem` blocktags - where blocktags = ["toc","index","para","formalpara","simpara", +isBlockElement (Elem e) = qName (elName e) `elem` blockTags +isBlockElement _ = False + +blockTags :: [String] +blockTags = ["toc","index","para","formalpara","simpara", "ackno","epigraph","blockquote","bibliography","bibliodiv", "biblioentry","glossee","glosseealso","glossary", "glossdiv","glosslist","chapter","appendix","preface", "bridgehead","sect1","sect2","sect3","sect4","sect5","section", - "refsect1","refsect2","refsect3","refsection", - "important","caution","note","tip","warning","qandadiv", + "refsect1","refsect2","refsect3","refsection", "qandadiv", "question","answer","abstract","itemizedlist","orderedlist", "variablelist","article","book","table","informaltable", "informalexample", "linegroup", - "screen","programlisting","example","calloutlist"] -isBlockElement _ = False + "screen","programlisting","example","calloutlist"] ++ admonitionTags + +admonitionTags :: [String] +admonitionTags = ["important","caution","note","tip","warning"] -- Trim leading and trailing newline characters -trimNl :: String -> String -trimNl = reverse . go . reverse . go - where go ('\n':xs) = xs - go xs = xs +trimNl :: Text -> Text +trimNl = T.dropAround (== '\n') -- meld text into beginning of first paragraph of Blocks. -- assumes Blocks start with a Para; if not, does nothing. addToStart :: Inlines -> Blocks -> Blocks addToStart toadd bs = case toList bs of (Para xs : rest) -> para (toadd <> fromList xs) <> fromList rest _ -> bs -- function that is used by both mediaobject (in parseBlock) -- and inlinemediaobject (in parseInline) -- A DocBook mediaobject is a wrapper around a set of alternative presentations getMediaobject :: PandocMonad m => Element -> DB m Inlines getMediaobject e = do (imageUrl, attr) <- case filterChild (named "imageobject") e of Nothing -> return (mempty, nullAttr) Just z -> case filterChild (named "imagedata") z of Nothing -> return (mempty, nullAttr) Just i -> let atVal a = attrValue a i w = case atVal "width" of "" -> [] d -> [("width", d)] h = case atVal "depth" of "" -> [] d -> [("height", d)] - atr = (atVal "id", words $ atVal "role", w ++ h) + atr = (atVal "id", T.words $ atVal "role", w ++ h) in return (atVal "fileref", atr) let getCaption el = case filterChild (\x -> named "caption" x || named "textobject" x || named "alt" x) el of Nothing -> return mempty Just z -> mconcat <$> mapM parseInline (elContent z) figTitle <- gets dbFigureTitle let (caption, title) = if isNull figTitle then (getCaption e, "") else (return figTitle, "fig:") fmap (imageWith attr imageUrl title) caption getBlocks :: PandocMonad m => Element -> DB m Blocks getBlocks e = mconcat <$> mapM parseBlock (elContent e) parseBlock :: PandocMonad m => Content -> DB m Blocks parseBlock (Text (CData CDataRaw _ _)) = return mempty -- DOCTYPE parseBlock (Text (CData _ s _)) = if all isSpace s then return mempty - else return $ plain $ trimInlines $ text s -parseBlock (CRef x) = return $ plain $ str $ map toUpper x + else return $ plain $ trimInlines $ text $ T.pack s +parseBlock (CRef x) = return $ plain $ str $ T.toUpper $ T.pack x parseBlock (Elem e) = case qName (elName e) of - "remark"-> return mempty - "toc" -> return mempty -- skip TOC, since in pandoc it's autogenerated - "index" -> return mempty -- skip index, since page numbers meaningless + "remark"-> skip + "toc" -> skip -- skip TOC, since in pandoc it's autogenerated + "index" -> skip -- skip index, since page numbers meaningless "para" -> parseMixed para (elContent e) "formalpara" -> do tit <- case filterChild (named "title") e of Just t -> (para . strong . (<> str ".")) <$> getInlines t Nothing -> return mempty (tit <>) <$> parseMixed para (elContent e) "simpara" -> parseMixed para (elContent e) "ackno" -> parseMixed para (elContent e) "epigraph" -> parseBlockquote "blockquote" -> parseBlockquote - "attribution" -> return mempty - "titleabbrev" -> return mempty - "authorinitials" -> return mempty + "attribution" -> skip + "titleabbrev" -> skip + "authorinitials" -> skip "bibliography" -> sect 0 "bibliodiv" -> sect 1 "biblioentry" -> parseMixed para (elContent e) "bibliomixed" -> parseMixed para (elContent e) "equation" -> para <$> equation e displayMath "informalequation" -> para <$> equation e displayMath "glosssee" -> para . (\ils -> text "See " <> ils <> str ".") <$> getInlines e "glossseealso" -> para . (\ils -> text "See also " <> ils <> str ".") <$> getInlines e "glossary" -> sect 0 "glossdiv" -> definitionList <$> mapM parseGlossEntry (filterChildren (named "glossentry") e) "glosslist" -> definitionList <$> mapM parseGlossEntry (filterChildren (named "glossentry") e) "chapter" -> getBlocks e "appendix" -> sect 0 "preface" -> sect 0 "bridgehead" -> para . strong <$> getInlines e "sect1" -> sect 1 "sect2" -> sect 2 "sect3" -> sect 3 "sect4" -> sect 4 "sect5" -> sect 5 "section" -> gets dbSectionLevel >>= sect . (+1) "refsect1" -> sect 1 "refsect2" -> sect 2 "refsect3" -> sect 3 "refsection" -> gets dbSectionLevel >>= sect . (+1) "important" -> divWith ("", ["important"], []) <$> getBlocks e - "caution" -> blockQuote . (para (strong $ str "Caution") <>) - <$> getBlocks e "note" -> divWith ("", ["note"], []) <$> getBlocks e - "tip" -> blockQuote . (para (strong $ str "Tip") <>) - <$> getBlocks e "warning" -> divWith ("", ["warning"], []) <$> getBlocks e - "area" -> return mempty - "areaset" -> return mempty - "areaspec" -> return mempty + l@_ | l `elem` admonitionTags -> parseAdmonition $ T.pack l + "area" -> skip + "areaset" -> skip + "areaspec" -> skip "qandadiv" -> gets dbSectionLevel >>= sect . (+1) "question" -> addToStart (strong (str "Q:") <> str " ") <$> getBlocks e "answer" -> addToStart (strong (str "A:") <> str " ") <$> getBlocks e "abstract" -> blockQuote <$> getBlocks e "calloutlist" -> bulletList <$> callouts "itemizedlist" -> bulletList <$> listitems "orderedlist" -> do let listStyle = case attrValue "numeration" e of "arabic" -> Decimal "loweralpha" -> LowerAlpha "upperalpha" -> UpperAlpha "lowerroman" -> LowerRoman "upperroman" -> UpperRoman _ -> Decimal let start = fromMaybe 1 $ (attrValue "override" <$> filterElement (named "listitem") e) >>= safeRead orderedListWith (start,listStyle,DefaultDelim) <$> listitems "variablelist" -> definitionList <$> deflistitems "figure" -> getFigure e "mediaobject" -> para <$> getMediaobject e - "caption" -> return mempty + "caption" -> skip "info" -> addMetadataFromElement e "articleinfo" -> addMetadataFromElement e - "sectioninfo" -> return mempty -- keywords & other metadata - "refsectioninfo" -> return mempty -- keywords & other metadata - "refsect1info" -> return mempty -- keywords & other metadata - "refsect2info" -> return mempty -- keywords & other metadata - "refsect3info" -> return mempty -- keywords & other metadata - "sect1info" -> return mempty -- keywords & other metadata - "sect2info" -> return mempty -- keywords & other metadata - "sect3info" -> return mempty -- keywords & other metadata - "sect4info" -> return mempty -- keywords & other metadata - "sect5info" -> return mempty -- keywords & other metadata - "chapterinfo" -> return mempty -- keywords & other metadata - "glossaryinfo" -> return mempty -- keywords & other metadata - "appendixinfo" -> return mempty -- keywords & other metadata + "sectioninfo" -> skip -- keywords & other metadata + "refsectioninfo" -> skip -- keywords & other metadata + "refsect1info" -> skip -- keywords & other metadata + "refsect2info" -> skip -- keywords & other metadata + "refsect3info" -> skip -- keywords & other metadata + "sect1info" -> skip -- keywords & other metadata + "sect2info" -> skip -- keywords & other metadata + "sect3info" -> skip -- keywords & other metadata + "sect4info" -> skip -- keywords & other metadata + "sect5info" -> skip -- keywords & other metadata + "chapterinfo" -> skip -- keywords & other metadata + "glossaryinfo" -> skip -- keywords & other metadata + "appendixinfo" -> skip -- keywords & other metadata "bookinfo" -> addMetadataFromElement e "article" -> modify (\st -> st{ dbBook = False }) >> addMetadataFromElement e >> getBlocks e "book" -> modify (\st -> st{ dbBook = True }) >> addMetadataFromElement e >> getBlocks e "table" -> parseTable "informaltable" -> parseTable "informalexample" -> divWith ("", ["informalexample"], []) <$> getBlocks e "linegroup" -> lineBlock <$> lineItems "literallayout" -> codeBlockWithLang "screen" -> codeBlockWithLang "programlisting" -> codeBlockWithLang "synopsis" -> synopsis "?xml" -> return mempty "title" -> return mempty -- handled in parent element "subtitle" -> return mempty -- handled in parent element - _ -> getBlocks e - where parseMixed container conts = do + _ -> skip >> getBlocks e + where skip = do + lift $ report $ IgnoredElement $ T.pack $ qName (elName e) + return mempty + + parseMixed container conts = do let (ils,rest) = break isBlockElement conts ils' <- (trimInlines . mconcat) <$> mapM parseInline ils let p = if ils' == mempty then mempty else container ils' case rest of [] -> return p (r:rs) -> do b <- parseBlock r x <- parseMixed container rs return $ p <> b <> x codeBlockWithLang = do let classes' = case attrValue "language" e of "" -> [] x -> [x] return $ codeBlockWith (attrValue "id" e, classes', []) - $ trimNl $ strContentRecursive e + $ trimNl $ T.pack $ strContentRecursive e synopsis = do return $ codeBlockWith (attrValue "id" e, ["synopsis"], []) - $ trimNl $ strContentRecursive e + $ trimNl $ T.pack $ strContentRecursive e parseBlockquote = do attrib <- case filterChild (named "attribution") e of Nothing -> return mempty Just z -> (para . (str "— " <>) . mconcat) <$> mapM parseInline (elContent z) contents <- getBlocks e return $ blockQuote (contents <> attrib) listitems = mapM getBlocks $ filterChildren (named "listitem") e callouts = mapM getBlocks $ filterChildren (named "callout") e deflistitems = mapM parseVarListEntry $ filterChildren (named "varlistentry") e parseVarListEntry e' = do let terms = filterChildren (named "term") e' let items = filterChildren (named "listitem") e' terms' <- mapM getInlines terms items' <- mapM getBlocks items return (mconcat $ intersperse (str "; ") terms', items') parseGlossEntry e' = do let terms = filterChildren (named "glossterm") e' let items = filterChildren (named "glossdef") e' terms' <- mapM getInlines terms items' <- mapM getBlocks items return (mconcat $ intersperse (str "; ") terms', items') parseTable = do let isCaption x = named "title" x || named "caption" x caption <- case filterChild isCaption e of Just t -> getInlines t Nothing -> return mempty let e' = fromMaybe e $ filterChild (named "tgroup") e let isColspec x = named "colspec" x || named "col" x let colspecs = case filterChild (named "colgroup") e' of Just c -> filterChildren isColspec c _ -> filterChildren isColspec e' let isRow x = named "row" x || named "tr" x headrows <- case filterChild (named "thead") e' of Just h -> case filterChild isRow h of Just x -> parseRow x Nothing -> return [] Nothing -> return [] bodyrows <- case filterChild (named "tbody") e' of Just b -> mapM parseRow $ filterChildren isRow b Nothing -> mapM parseRow $ filterChildren isRow e' let toAlignment c = case findAttr (unqual "align") c of Just "left" -> AlignLeft Just "right" -> AlignRight Just "center" -> AlignCenter _ -> AlignDefault let toWidth c = case findAttr (unqual "colwidth") c of Just w -> fromMaybe 0 - $ safeRead $ '0': filter (\x -> + $ safeRead $ "0" <> T.filter (\x -> (x >= '0' && x <= '9') - || x == '.') w + || x == '.') (T.pack w) Nothing -> 0 :: Double let numrows = case bodyrows of [] -> 0 xs -> maximum $ map length xs let aligns = case colspecs of [] -> replicate numrows AlignDefault cs -> map toAlignment cs let widths = case colspecs of [] -> replicate numrows 0 cs -> let ws = map toWidth cs tot = sum ws in if all (> 0) ws then map (/ tot) ws else replicate numrows 0 let headrows' = if null headrows then replicate numrows mempty else headrows return $ table caption (zip aligns widths) headrows' bodyrows isEntry x = named "entry" x || named "td" x || named "th" x parseRow = mapM (parseMixed plain . elContent) . filterChildren isEntry sect n = do isbook <- gets dbBook let n' = if isbook || n == 0 then n + 1 else n headerText <- case filterChild (named "title") e `mplus` (filterChild (named "info") e >>= filterChild (named "title")) of Just t -> getInlines t Nothing -> return mempty modify $ \st -> st{ dbSectionLevel = n } b <- getBlocks e let ident = attrValue "id" e modify $ \st -> st{ dbSectionLevel = n - 1 } return $ headerWith (ident,[],[]) n' headerText <> b lineItems = mapM getInlines $ filterChildren (named "line") e + -- | Admonitions are parsed into a div. Following other Docbook tools that output HTML, + -- we parse the optional title as a div with the @title@ class, and give the + -- block itself a class corresponding to the admonition name. + parseAdmonition label = do + -- elements can be directly nested inside an admonition block, use + -- it if it's there. It is unclear whether we should include the label in + -- the title: docbook references are ambiguous on that, and some implementations of admonitions + -- (e.g. asciidoctor) just use an icon in all cases. To be conservative, we don't + -- include the label and leave it to styling. + title <- case filterChild (named "title") e of + Just t -> divWith ("", ["title"], []) . plain <$> getInlines t + Nothing -> return $ mempty + -- this will ignore the title element if it is present + b <- getBlocks e + -- we also attach the label as a class, so it can be styled properly + return $ divWith (attrValue "id" e,[label],[]) (title <> b) getInlines :: PandocMonad m => Element -> DB m Inlines getInlines e' = (trimInlines . mconcat) <$> mapM parseInline (elContent e') strContentRecursive :: Element -> String strContentRecursive = strContent . (\e' -> e'{ elContent = map elementToStr $ elContent e' }) elementToStr :: Content -> Content elementToStr (Elem e') = Text $ CData CDataText (strContentRecursive e') Nothing elementToStr x = x parseInline :: PandocMonad m => Content -> DB m Inlines -parseInline (Text (CData _ s _)) = return $ text s +parseInline (Text (CData _ s _)) = return $ text $ T.pack s parseInline (CRef ref) = - return $ maybe (text $ map toUpper ref) text $ lookupEntity ref + return $ maybe (text $ T.toUpper $ T.pack ref) (text . T.pack) $ lookupEntity ref parseInline (Elem e) = case qName (elName e) of "equation" -> equation e displayMath "informalequation" -> equation e displayMath "inlineequation" -> equation e math "subscript" -> subscript <$> innerInlines "superscript" -> superscript <$> innerInlines "inlinemediaobject" -> getMediaobject e "quote" -> do qt <- gets dbQuoteType let qt' = if qt == SingleQuote then DoubleQuote else SingleQuote modify $ \st -> st{ dbQuoteType = qt' } contents <- innerInlines modify $ \st -> st{ dbQuoteType = qt } return $ if qt == SingleQuote then singleQuoted contents else doubleQuoted contents "simplelist" -> simpleList "segmentedlist" -> segmentedList "classname" -> codeWithLang "code" -> codeWithLang "filename" -> codeWithLang "literal" -> codeWithLang "computeroutput" -> codeWithLang "prompt" -> codeWithLang "parameter" -> codeWithLang "option" -> codeWithLang "optional" -> do x <- getInlines e return $ str "[" <> x <> str "]" "markup" -> codeWithLang "wordasword" -> emph <$> innerInlines "command" -> codeWithLang "varname" -> codeWithLang "function" -> codeWithLang "type" -> codeWithLang "symbol" -> codeWithLang "constant" -> codeWithLang "userinput" -> codeWithLang "varargs" -> return $ code "(...)" - "keycap" -> return (str $ strContent e) + "keycap" -> return (str $ T.pack $ strContent e) "keycombo" -> keycombo <$> mapM parseInline (elContent e) "menuchoice" -> menuchoice <$> mapM parseInline ( filter isGuiMenu $ elContent e) "xref" -> do content <- dbContent <$> get let linkend = attrValue "linkend" e let title = case attrValue "endterm" e of "" -> maybe "???" xrefTitleByElem (findElementById linkend content) - endterm -> maybe "???" strContent + endterm -> maybe "???" (T.pack . strContent) (findElementById endterm content) - return $ link ('#' : linkend) "" (text title) - "email" -> return $ link ("mailto:" ++ strContent e) "" - $ str $ strContent e - "uri" -> return $ link (strContent e) "" $ str $ strContent e + return $ link ("#" <> linkend) "" (text title) + "email" -> return $ link ("mailto:" <> T.pack (strContent e)) "" + $ str $ T.pack $ strContent e + "uri" -> return $ link (T.pack $ strContent e) "" $ str $ T.pack $ strContent e "ulink" -> link (attrValue "url" e) "" <$> innerInlines "link" -> do ils <- innerInlines let href = case findAttr (QName "href" (Just "http://www.w3.org/1999/xlink") Nothing) e of - Just h -> h - _ -> '#' : attrValue "linkend" e + Just h -> T.pack h + _ -> "#" <> attrValue "linkend" e let ils' = if ils == mempty then str href else ils - let attr = (attrValue "id" e, words $ attrValue "role" e, []) + let attr = (attrValue "id" e, T.words $ attrValue "role" e, []) return $ linkWith attr href "" ils' "foreignphrase" -> emph <$> innerInlines "phrase" -> case attrValue "revisionflag" e of "added" -> innerInlines "changed" -> innerInlines - "deleted" -> return mempty - "off" -> return mempty + "deleted" -> skip + "off" -> skip _ -> innerInlines "emphasis" -> case attrValue "role" e of "bold" -> strong <$> innerInlines "strong" -> strong <$> innerInlines "strikethrough" -> strikeout <$> innerInlines _ -> emph <$> innerInlines "footnote" -> (note . mconcat) <$> mapM parseBlock (elContent e) "title" -> return mempty - "affiliation" -> return mempty + "affiliation" -> skip -- Note: this isn't a real docbook tag; it's what we convert -- <?asciidor-br?> to in handleInstructions, above. A kludge to -- work around xml-light's inability to parse an instruction. "br" -> return linebreak - _ -> innerInlines - where innerInlines = (trimInlines . mconcat) <$> + _ -> skip >> innerInlines + where skip = do + lift $ report $ IgnoredElement $ T.pack $ qName (elName e) + return mempty + + innerInlines = (trimInlines . mconcat) <$> mapM parseInline (elContent e) codeWithLang = do let classes' = case attrValue "language" e of "" -> [] l -> [l] - return $ codeWith (attrValue "id" e,classes',[]) $ strContentRecursive e + return $ codeWith (attrValue "id" e,classes',[]) $ T.pack $ strContentRecursive e simpleList = (mconcat . intersperse (str "," <> space)) <$> mapM getInlines (filterChildren (named "member") e) segmentedList = do tit <- maybe (return mempty) getInlines $ filterChild (named "title") e segtits <- mapM getInlines $ filterChildren (named "segtitle") e segitems <- mapM (mapM getInlines . filterChildren (named "seg")) $ filterChildren (named "seglistitem") e let toSeg = mconcat . zipWith (\x y -> strong (x <> str ":") <> space <> y <> linebreak) segtits let segs = mconcat $ map toSeg segitems let tit' = if tit == mempty then mempty else strong tit <> linebreak return $ linebreak <> tit' <> segs keycombo = spanWith ("",["keycombo"],[]) . mconcat . intersperse (str "+") menuchoice = spanWith ("",["menuchoice"],[]) . mconcat . intersperse (text " > ") isGuiMenu (Elem x) = named "guimenu" x || named "guisubmenu" x || named "guimenuitem" x isGuiMenu _ = False findElementById idString content = asum [filterElement (\x -> attrValue "id" x == idString) el | Elem el <- content] -- Use the 'xreflabel' attribute for getting the title of a xref link; -- if there's no such attribute, employ some heuristics based on what -- docbook-xsl does. xrefTitleByElem el - | not (null xrefLabel) = xrefLabel - | otherwise = case qName (elName el) of + | not (T.null xrefLabel) = xrefLabel + | otherwise = case qName (elName el) of "chapter" -> descendantContent "title" el "section" -> descendantContent "title" el "sect1" -> descendantContent "title" el "sect2" -> descendantContent "title" el "sect3" -> descendantContent "title" el "sect4" -> descendantContent "title" el "sect5" -> descendantContent "title" el "cmdsynopsis" -> descendantContent "command" el "funcsynopsis" -> descendantContent "function" el - _ -> qName (elName el) ++ "_title" + _ -> T.pack $ qName (elName el) ++ "_title" where xrefLabel = attrValue "xreflabel" el - descendantContent name = maybe "???" strContent + descendantContent name = maybe "???" (T.pack . strContent) . filterElementName (\n -> qName n == name) -- | Extract a math equation from an element -- -- asciidoc can generate Latex math in CDATA sections. -- -- Note that if some MathML can't be parsed it is silently ignored! equation :: Monad m => Element -- ^ The element from which to extract a mathematical equation - -> (String -> Inlines) + -> (Text -> Inlines) -- ^ A constructor for some Inlines, taking the TeX code as input -> m Inlines equation e constructor = - return $ mconcat $ map constructor $ mathMLEquations ++ latexEquations + return $ mconcat $ map constructor $ mathMLEquations <> latexEquations where - mathMLEquations :: [String] + mathMLEquations :: [Text] mathMLEquations = map writeTeX $ rights $ readMath (\x -> qName (elName x) == "math" && qPrefix (elName x) == Just "mml") - (readMathML . showElement) + (readMathML . T.pack . showElement) - latexEquations :: [String] + latexEquations :: [Text] latexEquations = readMath (\x -> qName (elName x) == "mathphrase") - (concat . fmap showVerbatimCData . elContent) + (T.concat . fmap showVerbatimCData . elContent) readMath :: (Element -> Bool) -> (Element -> b) -> [b] readMath childPredicate fromElement = ( map (fromElement . everywhere (mkT removePrefix)) $ filterChildren childPredicate e ) --- | Get the actual text stored in a verbatim CData block. 'showContent' +-- | Get the actual text stored in a CData block. 'showContent' -- returns the text still surrounded by the [[CDATA]] tags. --- --- Returns 'showContent' if this is not a verbatim CData -showVerbatimCData :: Content -> String -showVerbatimCData (Text (CData CDataVerbatim d _)) = d -showVerbatimCData c = showContent c +showVerbatimCData :: Content -> Text +showVerbatimCData (Text (CData _ d _)) = T.pack d +showVerbatimCData c = T.pack $ showContent c + -- | Set the prefix of a name to 'Nothing' removePrefix :: QName -> QName removePrefix elname = elname { qPrefix = Nothing } diff --git a/documentation-tools/doc-converter/doctl b/documentation-tools/doc-converter/doctl index b236c91..9d5cc22 100755 --- a/documentation-tools/doc-converter/doctl +++ b/documentation-tools/doc-converter/doctl @@ -1,62 +1,67 @@ #!/bin/bash -PANDOC=/opt/pandoc/dist-newstyle/build/x86_64-linux/ghc-8.6.4/pandoc-2.7.1/x/pandoc/build/pandoc/pandoc -REMOTE='xreate@xreate.bigserver' +PANDOC=/opt/pandoc/dist/build/pandoc/pandoc +REMOTE_DOCS_PATH=/var/local/docs/ + DOC_CONTENT=( 'documentation/Transcend/transcend.xml' 'documentation/Transcend/ast-api.xml' 'documentation/Transcend/latetranscend.xml' 'documentation/Transcend/modules-api.xml' 'documentation/Transcend/latex-api.xml' 'documentation/Concepts/interpretation.xml' 'documentation/Concepts/containers.xml' 'documentation/Concepts/polymorphism.xml' 'documentation/Concepts/context.xml' 'documentation/Syntax/syntax.xml' 'documentation/Syntax/modules.xml' 'documentation/virtualization.xml' 'documentation/exploitation.xml' 'documentation/communication.xml' 'documentation/index.xml' 'documentation/build.xml' ) + +# MUST BE RUN FROM XREATE ROOT PWD=`pwd` Filename=`realpath $0` upload () { - convert_all /tmp/docs2 - rsync -e 'ssh -p24' -rtvz $Filename $REMOTE:/opt/doctl - rsync -e 'ssh -p24' -rtvz /tmp/docs2/ $REMOTE:/opt/documentation/ - rsync -e 'ssh -p24' -rtvz $PWD/documentation/manual.json $REMOTE:/opt/documentation/ + REMOTE=$1 + convert_all /tmp/docs +# rsync -e 'ssh -p24' -rtvz $Filename $REMOTE:/opt/doctl + rsync -e 'ssh -p24' -rtvz /tmp/docs/ $REMOTE:$REMOTE_DOCS_PATH + rsync -e 'ssh -p24' -rtvz $PWD/documentation/manual.json $REMOTE:$REMOTE_DOCS_PATH } convert (){ SOURCE_FILE=$1 DEST_FOLDER=$2 Name=$(basename $SOURCE_FILE) sed -e '/<?xxe-revisions/, /?>/ d' -e 's/<?xxe[^?]*?>//g' $SOURCE_FILE | \ $PANDOC \ -f docbook \ -t $PWD/documentation-tools/doc-converter/remarkup.lua \ -o $DEST_FOLDER/$Name.remarkup } convert_all (){ DEST_FOLDER=$1 + rm -r $DEST_FOLDER mkdir -p $DEST_FOLDER for Chapter in ${DOC_CONTENT[@]}; do convert $PWD/$Chapter $DEST_FOLDER done } case $1 in convert) convert $2 $3 ;; convert-all) convert_all $2 ;; upload) upload $2 ;; - *) echo "usage: $0 convert <SOURCE-FILE> <DEST-FOLDER> | convert-all <DEST-FOLDER> | upload";; + *) echo "usage: $0 convert <SOURCE-FILE> <DEST-FOLDER> | convert-all <DEST-FOLDER> | upload <server>";; esac diff --git a/documentation/manual.json b/documentation/manual.json index df326dd..b021798 100644 --- a/documentation/manual.json +++ b/documentation/manual.json @@ -1,36 +1,36 @@ { - "book": "Xreate Manual", + "book": "Xreate Language", "pages": [ {"title": "Basics", "pages": [ {"title": "Introduction", "slug": "/", "filename": "index.xml.remarkup", "subtitle": "General information about Xreate"}, {"title": "Build and Run", "slug": "build/", "filename": "build.xml.remarkup", "subtitle": "Getting started"}, {"title": "Syntax", "slug": "syntax/", "filename": "syntax.xml.remarkup", "subtitle": "Xreate syntax in detail"}, {"title": "Modules", "slug": "syntax/modules/", "filename": "modules.xml.remarkup", "subtitle": "Reuse and combine existing code in Xreate"} ]}, {"title": "Transcend", "pages": [ {"title": "Overview", "slug": "transcend/", "filename": "transcend.xml.remarkup", "subtitle": "Declarative level of Xreate"}, {"title": "Late Transcend", "slug": "transcend/late-transcend/", "filename": "latetranscend.xml.remarkup", "subtitle": "Reasoning at runtime"} ]}, {"title": "Concepts", "pages": [ {"title": "Polymorphism", "slug": "concepts/polymorphism/", "filename": "polymorphism.xml.remarkup", "subtitle": "Rules to configure and adjust program behaviour"}, {"title": "Context", "slug": "concepts/context/", "filename": "context.xml.remarkup", "subtitle": "Use the information about control flow and code hierachy"}, {"title": "Interpretation", "slug": "concepts/interpretation/", "filename": "interpretation.xml.remarkup", "subtitle": "Compile time computations"} ]}, {"title": "Extensions", "pages": [ {"title": "Containers", "slug": "concepts/containers/", "filename": "containers.xml.remarkup", "subtitle": "Automatic inference of the most apporpriate container implementation"}, {"title": "Communication", "slug": "communication/", "filename": "communication.xml.remarkup", "subtitle": "Safe usage of mutable and global variables"}, {"title": "Exploitation", "slug": "exploitation/", "filename": "exploitation.xml.remarkup", "subtitle": "Shared usage of the external resources: initialization and finalization"}, {"title": "Virtualization", "slug": "virtualization/", "filename": "virtualization.xml.remarkup", "subtitle": "Controls access to the external resources or different program's components"} ]}, {"title": "Transcend APIs", "pages": [ {"title": "AST API", "slug": "transcend/ast-api/", "filename": "ast-api.xml.remarkup", "subtitle": ""}, {"title": "Latex API", "slug": "transcend/latex-api/", "filename": "latex-api.xml.remarkup", "subtitle": ""}, {"title": "Modules API", "slug": "transcend/modules-api/", "filename": "modules-api.xml.remarkup", "subtitle": ""} ]} ] } diff --git a/tools/site/bootstrap.sh b/tools/site/bootstrap.sh new file mode 100755 index 0000000..49e839d --- /dev/null +++ b/tools/site/bootstrap.sh @@ -0,0 +1,17 @@ +#!/bin/sh +SCRIPT=`realpath $0` +PWD=`dirname $SCRIPT` + +# if [ "$#" -ne 1 ]; then +# echo "Usage: bootstrap.sh <Environment>" +# exit +# fi + +apt update +apt install puppet + +# Open access to a current directry for bootstrap +ln -s ${PWD} /etc/puppet/bootstrap + +puppet apply --test ${PWD}/puppet/bootstrap.pp +puppet apply --test ${PWD}/puppet/basics.pp diff --git a/tools/site/phabricatorctl b/tools/site/phabricatorctl new file mode 100755 index 0000000..071676e --- /dev/null +++ b/tools/site/phabricatorctl @@ -0,0 +1,116 @@ +#!/bin/bash +#os: ubuntu bionic + +#REMOTE=xreate@xreate.org +REMOTE='xreate@xreate.bigserver' + +PHP=php +PHP_FPM=php7.2-fpm + +set -x +Filename=`realpath $0` +Dir=`dirname $Filename` + +upload () { + DIR_UPLOAD=$Dir + rsync -e 'ssh -p24' -rtvz $DIR_UPLOAD/* $REMOTE:/opt/ +} + +refmap () { + ./phabricator/bin/celerity map + cd arcanist/ && ./bin/arc liberate && cd .. + $PHP ./libphutil/scripts/phutil_rebuild_map.php libphutil/src/ +} + +init () { + ln -s ../../../../phab-xreate/css ./phabricator/webroot/rsrc/css/xreate + refmap +} + +stop () { + echo Stop services + sudo /opt/phabricator/bin/phd stop --force + sudo systemctl stop $PHP_FPM + sudo systemctl stop nginx +} + +start () { + echo "Start services" + sudo /opt/phabricator/bin/phd start + sudo systemctl start $PHP_FPM + sudo systemctl start nginx +} + +upgrade () { + echo "Upgrade phabricator core" + cd /opt/phabricator + git pull + + echo "Upgrade arcanist" + cd /opt/arcanist + git pull + + echo "Upgrade libphutil" + cd /opt/libphutil + git pull + + echo "Upgrade Phab-Xreate" + cd /opt/phab-xreate + git pull + + echo "Upgrade storage" + /opt/phabricator/bin/storage upgrade --force; +} + +apply_patches () { + cd ./patches + git pull + + echo "Apply phabricator patches" + cd ../phabricator + git checkout -- * + git apply ../patches/patch-phabricator + + echo "Apply libphutil patches" + cd ../libphutil + git checkout -- * + git apply ../patches/patch-libphutil +} + +start_sshd () { + sudo /usr/sbin/sshd -f /etc/ssh/sshd_config_phabricator +} + +dump () { + ./phabricator/bin/storage dump --compress --output $1 +} + +dump_restore () { + gunzip -c $1 | mysql -uroot +} + +dump_repo () { + tar -C $2 -zcf $1 ./ +} + +reset_account () { + ./phabricator/bin/auth recover pgess +} + + + +case $1 in + first-start) start && start_sshd;; + start) start;; + stop) stop;; + restart) stop && start;; + upgrade) stop && upgrade;; + patch) stop && apply_patches && start;; + upload) upload;; + init) init;; + refmap) refmap;; + dump) dump $2;; + dump-restore) dump_restore $2;; + dump-repo) dump_repo $2 $3;; + *) echo "usage: $0 first-start | start | stop | restart | upgrade | patch | upload | init | refmap | dump <FILE> | dump-restore <dump-file> | dump-repo <Arch> <Repo>";; +esac diff --git a/tools/site/puppet/basics.pp b/tools/site/puppet/basics.pp new file mode 100644 index 0000000..d5719ae --- /dev/null +++ b/tools/site/puppet/basics.pp @@ -0,0 +1 @@ +include basics diff --git a/tools/site/puppet/bootstrap.pp b/tools/site/puppet/bootstrap.pp new file mode 100644 index 0000000..46d62f1 --- /dev/null +++ b/tools/site/puppet/bootstrap.pp @@ -0,0 +1,79 @@ +#============================================ +# Main Parameters + +$source_dir = '/etc/puppet/bootstrap/' + +#============================================ +# Managing Puppet itself + +$binpath = ['/usr/bin', '/usr/sbin', '/bin'] +$puppet_dir = '/etc/puppet/code/' +$modules_src_dir = "${source_dir}puppet/modules/" +$environments_src_dir = "${source_dir}puppet/conf/" + +# Standard Modules +$modules = [ + {'name'=> 'stdlib', 'vendor' => 'puppetlabs'}, + {'name'=> 'sudo', 'vendor' => 'saz'}, + {'name'=> 'ssh', 'vendor' => "saz"}, + {'name'=> 'systemd', 'vendor' => "camptocamp"}, + {'name'=> 'apt', 'vendor' => 'puppetlabs'}, + +# phabricator + {'name'=> 'cron', 'vendor' => 'puppet'} + ,{'name'=> 'vcsrepo', 'vendor' => 'puppetlabs'} + ,{'name'=> 'php', 'vendor' => 'puppet'} + ,{'name'=> 'debconf', "vendor" => "stm"} + ,{'name'=> 'git', "vendor" => "puppetlabs"} + ,{'name'=> 'logrotate', 'vendor' => "puppet"} + ,{'name'=> 'nodejs', 'vendor' => "puppet"} + ,{'name'=> 'mysql', 'vendor' => 'puppetlabs'} + ,{'name'=> 'nginx', 'vendor' => 'puppet'}, + +# others + {'name'=> 'nextcloud', 'vendor' => 'othalla'}, +] + +$modules.each | $module | { + exec {"puppet module install ${module['vendor']}/${module['name']} --environment ${environment}": + creates => "/etc/puppet/code/modules/${module['name']}", + path => $binpath, + logoutput => true + } +} + +# Inplace Modules +$modules_custom = ['zerotier', 'basics', 'phabricator', 'xreate_org'] + +$modules_custom.each | $module | { + file { "${puppet_dir}modules/${module}": + ensure => link, + target => "${modules_src_dir}${module}" + } +} + +# Environments +$environments = ['virtualbox', 'prod'] + +file{"${puppet_dir}environments": + ensure => directory; +} + +$environments.each | $environment | { + file{ + "${puppet_dir}environments/$environment": + ensure => directory; + + "${puppet_dir}environments/$environment/hiera.yaml": + ensure => file, + content => " + version: 5 + hierarchy: + - name: Common + path: common.yaml + + defaults: + data_hash: yaml_data + datadir: ${environments_src_dir}$environment/"; + } +} diff --git a/tools/site/puppet/conf/prod/common.yaml b/tools/site/puppet/conf/prod/common.yaml new file mode 100644 index 0000000..e795a90 --- /dev/null +++ b/tools/site/puppet/conf/prod/common.yaml @@ -0,0 +1,17 @@ +# 1) no http://, +# 2) MUST INCLUDE DOT +xreate_org::url : "xreate.org" +xreate_org::install_dir : "/opt/" +xreate_org::secrets_dir : "/tmp/secrets/" +xreate_org::db_user : "phabricator" +xreate_org::init_db : "/opt/init-data/phabricator.sql.gz" +xreate_org::init_repo : "/opt/init-data/xreate-repo.tar.gz" +xreate_org::xreate_docs_path : "/var/local/docs/" +xreate_org::doxy_docs_path : "/var/local/doxy-api/" +xreate_org::phabricator_ctl: "/opt/phabricatorctl" + +redirects: {} + #'mysql': + #enable: true + #src_port: 3308 + #dest_port: 3306 diff --git a/tools/site/puppet/conf/virtualbox/common.yaml b/tools/site/puppet/conf/virtualbox/common.yaml new file mode 100644 index 0000000..cef0323 --- /dev/null +++ b/tools/site/puppet/conf/virtualbox/common.yaml @@ -0,0 +1,21 @@ +# 1) no http://, +# 2) MUST INCLUDE DOT +xreate_org::url : "xreate.vm" +xreate_org::install_dir : "/opt/" +xreate_org::secrets_dir : "/tmp/secrets/" +xreate_org::db_user : "phabricator_test" +xreate_org::init_db : "/mnt/experiments/init-data/phabricator.sql.gz" +xreate_org::init_repo : "/mnt/experiments/init-data/xreate-repo.tar.gz" +xreate_org::xreate_docs_path : "/var/local/docs/" +xreate_org::doxy_docs_path : "/var/local/doxy-api/" +xreate_org::phabricator_ctl: "/mnt/experiments/phabricatorctl" + +redirects: + 'mysql': + enable: true + src_port: 3308 + dest_port: 3306 + + + + diff --git a/tools/site/puppet/modules/basics/manifests/init.pp b/tools/site/puppet/modules/basics/manifests/init.pp new file mode 100644 index 0000000..f22bd3a --- /dev/null +++ b/tools/site/puppet/modules/basics/manifests/init.pp @@ -0,0 +1,78 @@ +class basics +{ +#============================================ +# Main Parameters + +$zerotier_network = 'af78bf94366f0369' + +#============================================ +# Useful Packages + ensure_packages(['mc', 'joe', 'encfs', 'curl']) + + +#============================================ +# Users + + group { + default: + ensure => present, + system => true; + 'devs':; + 'phabricator':; + } + + user{ "xreate": + ensure => present, + uid => '1024', + home => '/home/xreate', managehome=> true, + shell => '/bin/bash', + groups => ['devs', 'phabricator'] + } + + class { 'sudo': + purge => false, + config_file_replace => false, + } + + sudo::conf { 'devs': + priority => 10, + content => '%devs ALL=(ALL) NOPASSWD: ALL', + } + +#============================================ +# Managing SSH + + class { 'ssh::server': + options => { + 'Port' => [24], + 'PasswordAuthentication' => 'no', + } + } + + ssh_authorized_key { 'pgess@regrabu': + user => 'xreate', + type => 'ssh-rsa', + key => 'AAAAB3NzaC1yc2EAAAADAQABAAABAQDCnsFfe5GSiiEpodGMSG9DnvSxDdiCjAOm2oqYfEDdpEgN+LFrgUu1mHQ+GB56SdOtxYbJlyV031CUyy3fUG6JJF7HdeP1hdINBVHQb0Ad4Jj+Kqefyia1ddhcuQiURan2xFDqlrisoZOHSllOAQfqjmS1vCgwtmlXp8nlFHxa9QmhrJw5NBEa6vgd16JmBuNGMLG81mxj4pHE6I7At/M9R0pJhlB4M9PuuLVpDMLNtihnqWovByQGgcrej/MoKO2wy2xzX21i2ilPLdLZkWBlkdahNF+QKaFANhodTOJBMCDjXDwGAsGgZ76eHyyqgJEf5LEv35T3QmUjLdCWBKnF', + } + +#============================================ +# ZeroTier + + class { 'zerotier': + network => $zerotier_network + } +} + + + +#============================================ +# Defines + +define group_member($user, $group) { + exec{"usermod -a -G ${group} ${user}": + unless => "/usr/bin/groups | /bin/grep ${group}", + user=> $user, + path => '/usr/sbin/' + } +} + diff --git a/tools/site/puppet/modules/basics/manifests/redir.pp b/tools/site/puppet/modules/basics/manifests/redir.pp new file mode 100644 index 0000000..e7bb812 --- /dev/null +++ b/tools/site/puppet/modules/basics/manifests/redir.pp @@ -0,0 +1,20 @@ +define basics::redir( + Boolean $enable, + + String $src_ip = '', + Integer $src_port, + + String $dest_ip = '', + Integer $dest_port, +) { + + ensure_packages(['redir', 'net-tools']) + + if $enable { + exec {"redir-${name}": + command => "redir -I ${name} ${src_ip}:${src_port} ${dest_ip}:${dest_port}", + unless => "netstat -nl | grep ${src_port}", + path => ['/bin', '/usr/bin/'] + } + } +} diff --git a/tools/site/puppet/modules/module-template/manifests/init.pp b/tools/site/puppet/modules/module-template/manifests/init.pp new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/tools/site/puppet/modules/module-template/manifests/init.pp @@ -0,0 +1 @@ + diff --git a/tools/site/puppet/modules/phabricator/manifests/config.pp b/tools/site/puppet/modules/phabricator/manifests/config.pp new file mode 100644 index 0000000..11dfeb9 --- /dev/null +++ b/tools/site/puppet/modules/phabricator/manifests/config.pp @@ -0,0 +1,193 @@ +# Configures Phabricator. +# +# @summary Configures Arcanist, libphutil and Phabricator. +# @private +# +class phabricator::config { + assert_private() + + $notify = Class['php::fpm::service'] + +# NOTE: Group 'phabricator' managed in basics/init.pp + user { + default: + ensure => 'present', + managehome => false, + system => true; + + $phabricator::daemon_user: + gid => $phabricator::group, + comment => 'Phabricator Daemons', + home => "${phabricator::install_dir}/phabricator/support/empty", + shell => '/usr/sbin/nologin'; + + $phabricator::vcs_user: + gid => $phabricator::group, + comment => 'Phabricator VCS', + home => $phabricator::repo_dir, + shell => '/bin/sh'; + } + + file { + default: + owner => 'root', + group => $phabricator::group; + + $phabricator::logs_dir: + ensure => 'directory', + group => undef, + mode => '0775'; + + $phabricator::repo_dir: + ensure => 'directory', + owner => $phabricator::www_user, + mode => '0750'; + + $phabricator::install_dir: + ensure => 'directory', + owner => $phabricator::admin_user; + + $phabricator::storage_dir: + ensure => 'directory', + owner => $phabricator::www_user; + + $phabricator::dumps_dir: + ensure => 'directory', + owner => $phabricator::admin_user; + + "/home/${phabricator::admin_user}/.ssh/bitbucket_id_rsa": + owner => 'xreate', + mode => 'u=rw,g=,o=', + source => "${phabricator::secrets_dir}bitbucket_id_rsa", + ensure => file; + + 'phabricator/conf/local.json': + ensure => 'file', + path => "${phabricator::install_dir}/phabricator/conf/local/local.json", + content => inline_template("<%= scope['phabricator::config'].to_json %>"), + mode => '0640', + notify => $notify, + owner => 'root', + group => $phabricator::group, + require => Vcsrepo['phabricator']; + + #Xreate Docs + "${phabricator::install_dir}phabricator/webroot/rsrc/css/xreate-docs": + ensure => link, + target => "${phabricator::install_dir}/xreate-docs/css", + owner => $phabricator::daemon_user, + group => $phabricator::group, + require => Vcsrepo['phabricator']; + + ["${phabricator::install_dir}xreate-docs/conf", $phabricator::xreate_docs_path]: + ensure => 'directory', + owner=>$phabricator::admin_user, + require=>Vcsrepo['xreate-docs']; + + "${phabricator::install_dir}xreate-docs/conf/local.json": + ensure => 'file', + content => inline_template("<%= scope['phabricator::xreate_docs_config'].to_json %>"), + require => [Vcsrepo['xreate-docs']]; + } + +#Configure Bitbucket: + sshkey { + 'bitbucket.org': + type => 'ssh-rsa', + key => 'AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==' + } + + class { 'ssh::client': + options => { + "Host *" => { + 'HashKnownHosts' => false, + } + } + } + + ::ssh::client::config::user { + $phabricator::admin_user: + ensure => present, + options => { + 'Host bitbucket.org' => { + 'Hostname' => 'bitbucket.org', + 'User' => 'git', + 'IdentityFile' => '~/.ssh/bitbucket_id_rsa' + } + } + } + + + logrotate::rule { 'phabricator': + ensure => 'present', + path => $phabricator::log_access_path, + compress => true, + delaycompress => true, + ifempty => false, + missingok => true, + rotate_every => 'week', + rotate => 40 + } + + # TODO: We should be able to tighten these permissions as follows: + # + # - `/usr/bin/git`, `/usr/bin/git-receive-pack`, `/usr/bin/git-upload-pack` + # and `/usr/lib/git-core/git-http-backend` should only be required if the + # node is //hosting// Diffusion repositories. + # - `/usr/bin/ssh` should only be required if the node is //serving// (either + # directly or by proxy) Diffusion repositories. + # + if $phabricator::manage_diffusion { + # lint:ignore:strict_indent + sudo::conf { "${phabricator::vcs_user}:${phabricator::daemon_user}": + ensure => 'present', + content => sprintf( + '%s ALL=(%s) SETENV: NOPASSWD: %s', + $phabricator::vcs_user, + "${phabricator::daemon_user}:${phabricator::group}", + join([ + '/usr/bin/git', + '/usr/bin/git-receive-pack', + '/usr/bin/git-upload-pack', + '/usr/bin/ssh', + ], ', '), + ), + } + # lint:endignore + + #PHP + include php::params + + # lint:ignore:strict_indent + sudo::conf { "${php::params::fpm_user}:${phabricator::daemon_user}": + ensure => 'present', + content => sprintf( + '%s ALL=(%s) SETENV: NOPASSWD: %s', + $php::params::fpm_user, + "${phabricator::daemon_user}:${phabricator::group}", + join([ + '/usr/bin/git', + '/usr/bin/ssh', + '/usr/lib/git-core/git-http-backend', + ], ', '), + ), + } + # lint:endignore + + # lint:ignore:strict_indent + ssh::server::config::setting { $phabricator::vcs_user: + key => "Match User ${phabricator::vcs_user}", + + # TODO: This seems quite hacky. + value => join([ + '', + "AuthorizedKeysCommand ${phabricator::install_dir}/phabricator/bin/ssh-auth", + "AuthorizedKeysCommandUser ${phabricator::vcs_user}", + ], "\n "), + } + # lint:endignore + + } + + # TODO: Add `logrotate` rules for Phabricator's access and SSH logs. +} diff --git a/tools/site/puppet/modules/phabricator/manifests/daemons.pp b/tools/site/puppet/modules/phabricator/manifests/daemons.pp new file mode 100644 index 0000000..d83f7ac --- /dev/null +++ b/tools/site/puppet/modules/phabricator/manifests/daemons.pp @@ -0,0 +1,82 @@ +# Class for installing Phabricator Daemons. +# +# @summary This class manages Phabricator Daemons. See +# {https://secure.phabricator.com/book/phabricator/article/managing_daemons/ +# Managing Daemons with phd}. +# +# @example +# class { 'phabricator': +# config_hash => { +# 'mysql.host' => 'localhost', +# 'mysql.user' => 'user', +# 'mysql.pass' => 'password', +# }, +# +# storage_upgrade => true, +# storage_upgrade_user => 'root', +# storage_upgrade_password => 'password', +# } +# +# include phabricator::daemons +# +# @param daemon Launch the specified daemon using `./bin/phd launch` instead of +# starting all of the daemon daemons. +# +class phabricator::daemons( + Optional[String] $daemon, +) { + # TODO: The `strict_indent` check doesn't seem to work properly here. See + # https://github.com/relud/puppet-lint-strict_indent-check/issues/11. + # + # lint:ignore:strict_indent + systemd::unit_file { 'phd.service': + ensure => 'file', + content => epp('phabricator/daemons.systemd.epp', { + command => "${phabricator::install_dir}/phabricator/bin/phd", + daemon => $daemon, + user => $phabricator::daemon_user, + group => $phabricator::group, + runtime_directory => $phabricator::runtime_directory, + }), + notify => Service['phd'], + } + # lint:endignore + + # TODO: Should we also specify `hasrestart => true`? According to the + # documentation the default value is `false`, although I am somewhat + # surprised by this. + service { 'phd': + ensure => 'running', + enable => true, + require => [ + Exec['systemctl-daemon-reload'], + File[$phabricator::logs_dir], + Group[$phabricator::group], + User[$phabricator::daemon_user] + ], + subscribe => [ + Class['php::cli'], + File['phabricator/conf/local.json'], + Vcsrepo['libphutil'], + Vcsrepo['phabricator'], + Vcsrepo['xreate-docs'], + ], + } + + # Restart the daemons if any PHP extensions are updated. + Php::Extension <| |> ~> Service['phd'] + + logrotate::rule { 'phd': + ensure => 'present', + path => "${phabricator::logs_dir}/daemons.log", + compress => true, + delaycompress => true, + ifempty => false, + missingok => true, + rotate => 4, + rotate_every => 'week', + su => true, + su_user => 'root', + su_group => $phabricator::group, + } +} diff --git a/tools/site/puppet/modules/phabricator/manifests/dumps.pp b/tools/site/puppet/modules/phabricator/manifests/dumps.pp new file mode 100644 index 0000000..6fd90b2 --- /dev/null +++ b/tools/site/puppet/modules/phabricator/manifests/dumps.pp @@ -0,0 +1,16 @@ +class phabricator::dumps { + cron::daily { + default: + #minute=>'*', + hour => '5', + user => $phabricator::admin_user; + + 'phab-db-dump': + command => "${phabricator::install_dir}phabricator/bin/storage dump --overwrite --compress --output ${phabricator::dumps_dir}xreate-db.sql.gz", + description => 'Phabricator DB dump'; + + 'phab-repo-dump': + command => "${phabricator::ctl} dump-repo ${phabricator::dumps_dir}xreate-repo.tar.gz ${phabricator::repo_dir}", + description => 'Phabricator repo dump' + } +} diff --git a/tools/site/puppet/modules/phabricator/manifests/init.pp b/tools/site/puppet/modules/phabricator/manifests/init.pp new file mode 100644 index 0000000..f7735a1 --- /dev/null +++ b/tools/site/puppet/modules/phabricator/manifests/init.pp @@ -0,0 +1,123 @@ +# Class for installing Phabricator. +# +# @summary This class configures and installs Phabricator. +# +# @example +# class { 'phabricator': +# config_hash => { +# 'mysql.host' => 'localhost', +# 'mysql.user' => 'user', +# 'mysql.pass' => 'password', +# }, +# +# storage_upgrade => true, +# storage_upgrade_user => 'root', +# storage_upgrade_password => 'password', +# } +# +# @param arcanist_revision The commit hash or branch for Arcanist. +# @param libphutil_revision The commit hash or branch for libphutil. +# @param phabricator_revision The commit hash or branch for Phabricator. +# @param config_hash Phabricator configuration. See +# {https://secure.phabricator.com/book/phabricator/article/advanced_configuration/ +# Configuration User Guide: Advanced Configuration}. +# @param install_fonts Whether to install additional fonts. +# @param manage_diffusion Whether to configure the host in order to be able to +# serve (either directly or by proxying to another host in the cluster). See +# {https://secure.phabricator.com/book/phabricator/article/diffusion_hosting/ +# Diffusion User Guide: Repository Hosting}. +# @param storage_upgrade A flag to enable storage upgrades. See +# {https://secure.phabricator.com/book/phabricator/article/configuration_guide/#storage-configuring-mysql +# Storage: Configuring MySQL}. +# @param storage_upgrade_user The MySQL user with which to execute +# `bin/storage upgrade`. +# @param storage_upgrade_password The MySQL password for the storage upgrade +# user. +# +# @param daemon_user +# @param group +# @param install_dir +# @param logs_dir +# @param pid_dir +# @param repo_dir +# @param vcs_user +# +class phabricator( + String $server_url, + + String $arcanist_url, + String $phabricator_url, + String $libphutil_url, + String $xreate_docs_url, + String $init_db, + String $init_repo, + String $ctl, + + Hash[String, Data] $config_hash, + Boolean $install_fonts, + Boolean $manage_diffusion, + Optional[String] $storage_upgrade_user, + Optional[String] $storage_upgrade_password, + + String $admin_user, + String $daemon_user, + String $www_user, + String $vcs_user, + String $group, + + Stdlib::Unixpath $install_dir, + Stdlib::Unixpath $logs_dir, + Stdlib::Unixpath $pid_dir, + Stdlib::Unixpath $repo_dir, + Stdlib::Unixpath $storage_dir, + Stdlib::Unixpath $dumps_dir, + + String $secrets_dir, + String $xreate_docs_path, + +) { + + $fpm_socket = "/run/php/php-fpm.sock" + + assert_type(String, $storage_upgrade_user) + assert_type(String, $storage_upgrade_password) + + $log_access_path = "${logs_dir}phabricator.log" + + if $pid_dir =~ /^\/run\// { + $runtime_directory = regsubst($pid_dir, /^\/run\//, '') + } else { + fail('$pid_dir must be a descendent of /run.') + } + + $config = merge( + $config_hash, + { + 'diffusion.ssh-user' => $vcs_user, + 'environment.append-paths' => ['/usr/lib/git-core', '/usr/bin', '/bin'], #$PATH + 'log.access.path' => $log_access_path, + 'log.ssh.path' => "${logs_dir}/ssh.log", + 'phd.log-directory' => $logs_dir, + 'phd.user' => $daemon_user, + 'repository.default-local-path' => $repo_dir, + } + ) + + $xreate_docs_config = { + 'xreate.book.project' => "${phabricator::xreate_docs_path}manual.json" + } + + #include phabricator::aphlict + + class { '::phabricator::php':} + class { '::phabricator::nginx':} + + include phabricator::config + class { 'phabricator::install': require => Class['::phabricator::php'] } + + class {'phabricator::daemons': + daemon => undef + } + + include phabricator::dumps +} diff --git a/tools/site/puppet/modules/phabricator/manifests/install.pp b/tools/site/puppet/modules/phabricator/manifests/install.pp new file mode 100644 index 0000000..eedaff3 --- /dev/null +++ b/tools/site/puppet/modules/phabricator/manifests/install.pp @@ -0,0 +1,178 @@ +# Installs Phabricator. +# +# @summary Installs Arcanist, libphutil and Phabricator. +# @private +# +class phabricator::install { + assert_private() + + # The `php::packages` class requires `Class['apt::update']` unconditionally, + # but the `apt::update` class may not have been defined. See + # https://github.com/voxpupuli/puppet-php/pull/323. + include apt + include git + + $notify = Class['php::fpm::service'] + + # Ensure that the CLI is installed before any extensions are installed. + Class['php::cli'] -> Php::Extension <| |> + + vcsrepo { + default: + ensure => 'latest', + provider => 'git', + user => $phabricator::admin_user, + group => $phabricator::group, + require => Ssh::Client::Config::User[$phabricator::admin_user], + notify => $notify; + + 'arcanist': + path => "${phabricator::install_dir}/arcanist", + source => $phabricator::arcanist_url; + + 'libphutil': + path => "${phabricator::install_dir}/libphutil", + source => $phabricator::libphutil_url; + + 'phabricator': + path => "${phabricator::install_dir}/phabricator", + source => $phabricator::phabricator_url; + + 'xreate-docs': + path => "${phabricator::install_dir}/xreate-docs", + source => $phabricator::xreate_docs_url + } + + class refresh { + exec { + default: + refreshonly => true, + user => $phabricator::admin_user, + group => $phabricator::group, + cwd => "${phabricator::install_dir}", + path =>['/bin', '/usr/bin'], + logoutput => true, + subscribe => [ + Vcsrepo['xreate-docs'], + File['phabricator/conf/local.json'] + ]; + + 'arc liberate': + command => "${phabricator::install_dir}arcanist/bin/arc liberate --upgrade", + cwd => "${phabricator::install_dir}xreate-docs"; + + "${phabricator::install_dir}libphutil/scripts/phutil_rebuild_map.php libphutil/src/":; + + 'celerity map': + command => "${phabricator::install_dir}phabricator/bin/celerity map"; + } + } + + class storage { + $storage_upgrade_flags = shellquote( + [ + '--force', + "--user=${phabricator::storage_upgrade_user}", + "--password=${phabricator::storage_upgrade_password}", + ] + ) + + if !empty($phabricator::init_db) { + notice ("Restore DB from dump!") + exec {'db update': + command => "${phabricator::ctl} dump-restore ${phabricator::init_db}", + timeout => 1800, + onlyif => [ + "test -e ${phabricator::ctl}", + "test -e ${phabricator::init_db}", + ], + unless => '/usr/bin/mysql -uroot -e "show databases;" | grep phabricator', + path => ['/bin', '/usr/bin'], + subscribe => Class['phabricator::mysql'], + notify => [Class['php::fpm::service'], Service['phd']] + } + } else { + exec { 'db update': + command => Sensitive.new("${phabricator::install_dir}phabricator/bin/storage upgrade ${storage_upgrade_flags}"), + unless => '/usr/bin/mysql -uroot -e "show databases;" | grep phabricator', + timeout => 0, + user => $phabricator::admin_user, + group => $phabricator::group, + path =>['/bin', '/usr/bin'], + logoutput => true, + require => [ + Class['php::cli'], + File['phabricator/conf/local.json'], + Vcsrepo['arcanist'], + Vcsrepo['libphutil'] + ], + subscribe => [ + Vcsrepo['phabricator'], + Class['phabricator::mysql'], + File['phabricator/conf/local.json'], + ], + notify => [Class['php::fpm::service'], Service['phd']] + } + } + } + + class{'phabricator::install::refresh': } + class{'phabricator::install::storage': require=>Class['phabricator::install::refresh']} + + #Repo + archive {"${phabricator::init_repo}": + extract => true, + extract_path => $phabricator::repo_dir, + creates => "${phabricator::repo_dir}/1", + cleanup => false, + } + + $repositories = ['rXR'] + $repositories.each | $rep | { + exec{"${phabricator::install_dir}phabricator/bin/repository update ${rep}": + refreshonly => true, + subscribe => Archive["${phabricator::init_repo}"], + path => '/usr/bin/', + logoutput => true + } + } + + + # These packages are required in order to compile XHPAST. + ensure_packages(['g++', 'make']) + + exec { 'build_xhpast.php': + command => "${phabricator::install_dir}/libphutil/scripts/build_xhpast.php", + refreshonly => true, + require => [ + Class['php::cli'], + Package['g++'], + Package['make'], + ], + subscribe => Vcsrepo['libphutil'], + } + + if $phabricator::install_fonts { + debconf { 'msttcorefonts/accepted-mscorefonts-eula': + ensure => 'present', + package => 'ttf-mscorefonts-installer', + type => 'select', + value => bool2str(true), + before => Package['ttf-mscorefonts-installer'], + } + + package { 'ttf-mscorefonts-installer': + ensure => 'latest', + } + + $font_file_ensure = 'link' + } else { + $font_file_ensure = 'absent' + } + + file { "${phabricator::install_dir}/phabricator/resources/font/impact.ttf": + ensure => $font_file_ensure, + target => '/usr/share/fonts/truetype/msttcorefonts/Impact.ttf', + require => Vcsrepo['phabricator'], + } +} diff --git a/tools/site/puppet/modules/phabricator/manifests/mysql.pp b/tools/site/puppet/modules/phabricator/manifests/mysql.pp new file mode 100644 index 0000000..a70901c --- /dev/null +++ b/tools/site/puppet/modules/phabricator/manifests/mysql.pp @@ -0,0 +1,38 @@ +define mysqldb_user( $user, $password ) { + exec { "${name}": + unless => "mysql -u${user} -p${password}", + command => "/usr/bin/mysql -uroot -e \"CREATE USER '${user}'@'%' IDENTIFIED BY '${password}'; grant all privileges on *.* to '${user}'@'%';\"", + require => Service["mysqld"], + path => '/usr/bin', + } +} + +class phabricator::mysql( + String $user, + String $password +) +{ + class { '::mysql::server': + package_name => 'mariadb-server', + remove_default_accounts => true, + restart => true, + override_options => { + 'mysqld'=> { + 'bind-address' => '127.0.0.1', + 'max_allowed_packet' => '33554432', + 'sql_mode' => 'STRICT_ALL_TABLES', + 'innodb_buffer_pool_size' => '1600M', + 'local_infile' => '0', + } + } + } + + service{'mariadb': + ensure => running, + } + + mysqldb_user{'mysql-phabricator-user': + user => $user, + password => $password + } +} diff --git a/tools/site/puppet/modules/phabricator/manifests/nginx.pp b/tools/site/puppet/modules/phabricator/manifests/nginx.pp new file mode 100644 index 0000000..03071ed --- /dev/null +++ b/tools/site/puppet/modules/phabricator/manifests/nginx.pp @@ -0,0 +1,55 @@ +class phabricator::nginx { + class {'nginx': + client_max_body_size => '32M' + } + + $access_log = "${nginx::params::log_dir}/${phabricator::server_url}.${nginx::params::http_access_log_file}" + $error_log = "${nginx::params::log_dir}/${phabricator::server_url}.${nginx::params::nginx_error_log_file}" + + nginx::resource::server {$phabricator::server_url: + ensure => present, + use_default_location => false, + www_root => "${phabricator::install_dir}phabricator/webroot", + access_log => $access_log, + error_log => $error_log, + rewrite_www_to_non_www => true, + notify => Class['php::fpm::service'] + } + + nginx::resource::location{'/': + ensure => present, + server => $phabricator::server_url, + index_files => ['index.php'], + rewrite_rules => ['^/(.*)$ /index.php?__path__=/$1 last'] + } + + nginx::resource::location{'/index.php': + ensure => present, + server => $phabricator::server_url, + fastcgi => "unix:${phabricator::fpm_socket}", + fastcgi_index => 'index.php', + fastcgi_param => { + 'REDIRECT_STATUS'=> '200', + 'SCRIPT_FILENAME'=> '$document_root$fastcgi_script_name', + 'QUERY_STRING'=> '$query_string', + 'REQUEST_METHOD'=> '$request_method', + 'CONTENT_TYPE'=> '$content_type', + 'CONTENT_LENGTH'=> '$content_length', + 'SCRIPT_NAME'=> '$fastcgi_script_name', + 'GATEWAY_INTERFACE'=> 'CGI/1.1', + 'SERVER_SOFTWARE'=> 'nginx/$nginx_version', + 'REMOTE_ADDR'=> '$remote_addr' + } + } + + logrotate::rule { 'nginx': + ensure => 'present', + path => [$access_log, $error_log], + compress => true, + delaycompress => true, + ifempty => false, + missingok => true, + rotate_every => 'week', + rotate => 40 + } +} diff --git a/tools/site/puppet/modules/phabricator/manifests/php.pp b/tools/site/puppet/modules/phabricator/manifests/php.pp new file mode 100644 index 0000000..c484149 --- /dev/null +++ b/tools/site/puppet/modules/phabricator/manifests/php.pp @@ -0,0 +1,43 @@ +class phabricator::php { + + # TODO: It's not currently possible to test for warnings with `rspec-puppet`. + # See https://github.com/rodjek/rspec-puppet/issues/108. + if $facts['phpversion'] != undef and versioncmp($facts['phpversion'], '7.0.0') >= 0 and versioncmp($facts['phpversion'], '7.1.0') < 0 { + warning('Phabricator does not support PHP 7.0. See https://secure.phabricator.com/T12101.') + } + + class { '::php::globals': php_version => '7.2'} + class{'::php': + ensure => 'latest', + fpm => true, + fpm_service_ensure => 'running', + settings => { + 'Date/date.timezone' => 'Europe/Paris', + +# https://secure.phabricator.com/book/phabricator/article/configuring_file_storage/ + 'PHP/post_max_size' => '32M', + 'PHP/memory_limit' => '-1', + 'PHP/upload_max_filesize' => '32M', + + 'opcache/opcache.validate_timestamps' => '0', + 'apcu/apc.shm_size' => '256M' + } + } + + php::fpm::pool { 'phabricator': + user => $phabricator::www_user, + group => $phabricator::group, + listen => $phabricator::fpm_socket, + listen_owner => 'www-data', + listen_group => 'www-data' + } + + php::extension { + ['curl', 'gd', 'mbstring', 'zip']: ; + + 'apcu': + package_prefix => 'php-'; + } + + ensure_packages('php-mysql') +} diff --git a/tools/site/puppet/modules/phabricator/templates/aphlict.systemd.epp b/tools/site/puppet/modules/phabricator/templates/aphlict.systemd.epp new file mode 100644 index 0000000..a5826e2 --- /dev/null +++ b/tools/site/puppet/modules/phabricator/templates/aphlict.systemd.epp @@ -0,0 +1,24 @@ +<%- | + Stdlib::Unixpath $command, + String $user, + String $group, + String $runtime_directory, +| -%> +[Unit] +Description=Aphlict +Documentation=https://secure.phabricator.com/book/phabricator/article/notifications/ +Requires=network.target +After=network.target + +[Service] +Type=forking +ExecStart=<%= $command %> start +ExecReload=<%= $command %> restart +ExecStop=<%= $command %> stop +Restart=on-failure +User=<%= $user %> +Group=<%= $group %> +RuntimeDirectory=<%= $runtime_directory %> + +[Install] +WantedBy=multi-user.target diff --git a/tools/site/puppet/modules/phabricator/templates/daemons.systemd.epp b/tools/site/puppet/modules/phabricator/templates/daemons.systemd.epp new file mode 100644 index 0000000..aac677d --- /dev/null +++ b/tools/site/puppet/modules/phabricator/templates/daemons.systemd.epp @@ -0,0 +1,32 @@ +<% | + Stdlib::Unixpath $command, + Optional[String] $daemon, + String $user, + String $group, + String $runtime_directory, +| -%> +[Unit] +Description=Phabricator Daemons +Documentation=https://secure.phabricator.com/book/phabricator/article/managing_daemons/ +Requires=network.target +After=network.target + +[Service] +Type=forking +<% if $daemon { -%> +ExecStart=<%= $command %> launch <%= $daemon %> +<% } else { -%> +ExecStart=<%= $command %> start +<% } -%> +<%# +# TODO: We should probably use `bin/phd reload`, although certain resources +# (such as `Class['php::cli']`) should trigger a `restart` rather than a `reload`. +-%> +ExecReload=<%= $command %> restart --force +ExecStop=<%= $command %> stop --force +User=<%= $user %> +Group=<%= $group %> +RuntimeDirectory=<%= $runtime_directory %> + +[Install] +WantedBy=multi-user.target diff --git a/tools/site/puppet/modules/phabricator/types/revision.pp b/tools/site/puppet/modules/phabricator/types/revision.pp new file mode 100644 index 0000000..cba1097 --- /dev/null +++ b/tools/site/puppet/modules/phabricator/types/revision.pp @@ -0,0 +1,4 @@ +type Phabricator::Revision = Variant[ + Enum['master', 'stable'], + Pattern[/^[0-9a-f]{40}$/], +] diff --git a/tools/site/puppet/modules/xreate_org/manifests/backup.pp b/tools/site/puppet/modules/xreate_org/manifests/backup.pp new file mode 100644 index 0000000..143ce1a --- /dev/null +++ b/tools/site/puppet/modules/xreate_org/manifests/backup.pp @@ -0,0 +1,13 @@ +# class xreate_org::backup{ +# include borg +# +# file { +# "${phabricator::backups_dir}/phabricator": +# ensure => 'directory', +# owner => $phabricator::daemon_user; +# } +# +# exec{ +# command=> "borg init -e keyfile-blake2 ${phabricator::backups_dir}/phabricator" +# } +# } diff --git a/tools/site/puppet/modules/xreate_org/manifests/init.pp b/tools/site/puppet/modules/xreate_org/manifests/init.pp new file mode 100644 index 0000000..dfb8535 --- /dev/null +++ b/tools/site/puppet/modules/xreate_org/manifests/init.pp @@ -0,0 +1,168 @@ +class xreate_org( + String $url, + String $install_dir, + String $db_user, + String $secrets_dir, + String $init_db, + String $xreate_docs_path, + String $doxy_docs_path, + String $phabricator_ctl, + String $init_repo, +){ + $db_pass = file("${secrets_dir}mysql-pwd-${db_user}")[0, -2] + $storage_dir = '/var/local/storage/' + $backups_dir = '/var/local/backups/' + $admin_user = 'xreate' #Defined in basics/init.pp! + $group = 'phabricator' #Defined in basics/init.pp! + + include basics + + class {'phabricator::mysql': + user => $db_user, + password => $db_pass + } + + class { 'phabricator': + server_url => $url, + secrets_dir => $secrets_dir, + init_db =>$init_db, + xreate_docs_path => $xreate_docs_path, + ctl => $phabricator_ctl, + + #DB + storage_upgrade_user => $db_user, + storage_upgrade_password => $db_pass, + + #REPO + init_repo => $init_repo, + + #USERS: + admin_user => $admin_user, + daemon_user => 'phabd', + vcs_user => 'xreate-repo', + www_user => 'www-data', + group => $group, + + #URLS: + arcanist_url => 'ssh://git@bitbucket.org/pgess/xreate-arcanist.git', + phabricator_url => 'ssh://git@bitbucket.org/pgess/xreate-phabricator.git', + libphutil_url => 'ssh://git@bitbucket.org/pgess/xreate-libphutil.git', + xreate_docs_url => 'ssh://git@bitbucket.org/pgess/xreate-docs.git', + + #Path stored in DB: phabrcator_repository.repository.localPath + repo_dir => '/var/local/repo/', + storage_dir => $storage_dir, + dumps_dir => '/var/local/dumps/', + install_dir => $install_dir, + logs_dir => '/var/log/', + pid_dir => '/run/', + + install_fonts => false, + manage_diffusion => true, + + config_hash => { + + #EMAIL: + "metamta.default-address"=> "bot@xreate.org", + "cluster.mailers" => [ + { + "key" => "xreate-mailer", + "type" => "smtp", + "options" => { + "host"=> "smtp.zoho.com", + "port"=> 465, + "user" => "bot@xreate.org", + "password" => "UeqiFxzkBdF1Ln0uwcTn", + "protocol" => "ssl" + } + }], + + "phabricator.base-uri" => "http://${url}", + "phabricator.tail-title" => "Xreate", + "phabricator.show-prototypes" => true, + "storage.default-namespace"=> "phabricator", + 'storage.local-disk.path' => $storage_dir, + + 'mysql.host' => '127.0.0.1', + 'mysql.user' => $db_user, + 'mysql.pass' => $db_pass, + + #MODULES: + 'load-libraries' => { + 'xreate' => "${install_dir}/xreate-docs/src/" + }, + + #DIFFUSION: + 'diffusion.allow-http-auth' => true, + + #UI: + 'ui.header-color' => 'dark', + 'ui.logo' => { "logoImagePHID"=> null, "wordmarkText" => "Xreate" }, + 'ui.footer-items'=> [ + { "name"=> "Email: pr.h7@xreate.org" }, + { "name"=> "2019 Xreate.org" }, + { "name"=> "Powered by Phabricator" } + ], + + 'phabricator.uninstalled-applications'=> { + 'PhabricatorConpherenceApplication' => true, + 'PhabricatorNuanceApplication' => true, + 'PhabricatorPholioApplication' => true, + 'PhabricatorAlmanacApplication' => true, + 'PhabricatorBadgesApplication' => true, + 'PhabricatorCalendarApplication' => true, + 'PhabricatorChatLogApplication' => true, + 'PhabricatorCountdownApplication' => true, + 'PhabricatorDivinerApplication' => true, + 'PhabricatorDrydockApplication' => true, + 'PhabricatorFactApplication' => true, + 'PhabricatorFlagsApplication' => true, + 'PhabricatorFundApplication' => true, + 'PhabricatorHarbormasterApplication' => true, + 'PhabricatorHeraldApplication' => true, + 'PhabricatorLegalpadApplication' => true, + 'PhabricatorMacroApplication' => true, + 'PhabricatorOwnersApplication' => true, + 'PhabricatorPackagesApplication' => true, + 'PhabricatorPhluxApplication' => true, + 'PhabricatorPhortuneApplication' => true, + 'PhabricatorPhragmentApplication' => true, + 'PhabricatorPhrequentApplication' => true, + 'PhabricatorPhurlApplication' => true, + 'PhabricatorReleephApplication' => true, + 'PhabricatorSlowvoteApplication' => true, + 'PhabricatorTokensApplication' => true, + 'PhabricatorMultimeterApplication' => true, + 'PhabricatorPHPASTApplication' => true, + 'PhabricatorUIExamplesApplication' => true, + 'PhabricatorXHProfApplication' => true, + 'PhabricatorOAuthServerApplication' => true + } + }, + } + + #remove default NGINX sites + $nginx_sites = "${nginx::params::conf_dir}/sites-enabled" + file {"${nginx_sites}/default": + ensure => absent + } + + #Doxygen Documentation + file{ + $doxy_docs_path: + ensure => 'directory', + owner=>$phabricator::admin_user, + group => $group; + } + + nginx::resource::location{ '^~ /api': + location_alias => "${doxy_docs_path}", + index_files => ['index.html'], + server => $xreate_org::url, + } + + #Port redirects + $redirects = hiera_hash('redirects',{}) + notice($redirects) + create_resources('basics::redir',$redirects) +} diff --git a/tools/site/puppet/modules/zerotier/files/zerotier-install b/tools/site/puppet/modules/zerotier/files/zerotier-install new file mode 100755 index 0000000..d95bfa9 --- /dev/null +++ b/tools/site/puppet/modules/zerotier/files/zerotier-install @@ -0,0 +1,4 @@ +#!/bin/sh + +curl -s 'https://raw.githubusercontent.com/zerotier/ZeroTierOne/master/doc/contact%40zerotier.com.gpg' | gpg --import && \ +if z=$(curl -s 'https://install.zerotier.com/' | gpg); then echo "$z" | sudo bash; fi diff --git a/tools/site/puppet/modules/zerotier/manifests/init.pp b/tools/site/puppet/modules/zerotier/manifests/init.pp new file mode 100644 index 0000000..e60826b --- /dev/null +++ b/tools/site/puppet/modules/zerotier/manifests/init.pp @@ -0,0 +1,34 @@ +#============================================ +# ZeroTier + +class zerotier ( + String $network, + Array $binpath = ['/usr/bin', '/usr/sbin', '/bin'] +) { + file { "/tmp/zerotier-install": + source => "puppet:///modules/zerotier/zerotier-install", + mode => 'u+x', + ensure => file, + force => true + } + +# $cmd = file('zerotier/zerotier-install') +# notice($cmd) + + exec{ "/tmp/zerotier-install": + unless => 'apt list --installed | grep zerotier-one', + path => $binpath, + logoutput => true + } + + service { 'zerotier-one': + ensure => running, + enable => true, + } + + exec{ "zerotier-cli join ${network}": + unless => "zerotier-cli listnetworks | grep ${network}", + path => $binpath, + logoutput => true + } +} diff --git a/tools/site/puppet/xreate_org.pp b/tools/site/puppet/xreate_org.pp new file mode 100644 index 0000000..c55f808 --- /dev/null +++ b/tools/site/puppet/xreate_org.pp @@ -0,0 +1,11 @@ +include xreate_org + +# exec {'refresh': +# command => "/bin/true", +# notify => [ +# Exec['bin/storage upgrade'], +# Class['::php::fpm'], +# Class['::nginx'], +# ] +# Exec['bin/storage upgrade'] +# }