droiddoc.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. // Copyright 2018 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package java
  15. import (
  16. "fmt"
  17. "path/filepath"
  18. "strings"
  19. "github.com/google/blueprint/proptools"
  20. "android/soong/android"
  21. "android/soong/java/config"
  22. )
  23. func init() {
  24. RegisterDocsBuildComponents(android.InitRegistrationContext)
  25. }
  26. func RegisterDocsBuildComponents(ctx android.RegistrationContext) {
  27. ctx.RegisterModuleType("doc_defaults", DocDefaultsFactory)
  28. ctx.RegisterModuleType("droiddoc", DroiddocFactory)
  29. ctx.RegisterModuleType("droiddoc_host", DroiddocHostFactory)
  30. ctx.RegisterModuleType("droiddoc_exported_dir", ExportedDroiddocDirFactory)
  31. ctx.RegisterModuleType("javadoc", JavadocFactory)
  32. ctx.RegisterModuleType("javadoc_host", JavadocHostFactory)
  33. }
  34. type JavadocProperties struct {
  35. // list of source files used to compile the Java module. May be .java, .logtags, .proto,
  36. // or .aidl files.
  37. Srcs []string `android:"path,arch_variant"`
  38. // list of source files that should not be used to build the Java module.
  39. // This is most useful in the arch/multilib variants to remove non-common files
  40. // filegroup or genrule can be included within this property.
  41. Exclude_srcs []string `android:"path,arch_variant"`
  42. // list of package names that should actually be used. If this property is left unspecified,
  43. // all the sources from the srcs property is used.
  44. Filter_packages []string
  45. // list of java libraries that will be in the classpath.
  46. Libs []string `android:"arch_variant"`
  47. // If set to false, don't allow this module(-docs.zip) to be exported. Defaults to true.
  48. Installable *bool
  49. // if not blank, set to the version of the sdk to compile against.
  50. // Defaults to compiling against the current platform.
  51. Sdk_version *string `android:"arch_variant"`
  52. // When targeting 1.9 and above, override the modules to use with --system,
  53. // otherwise provides defaults libraries to add to the bootclasspath.
  54. // Defaults to "none"
  55. System_modules *string
  56. Aidl struct {
  57. // Top level directories to pass to aidl tool
  58. Include_dirs []string
  59. // Directories rooted at the Android.bp file to pass to aidl tool
  60. Local_include_dirs []string
  61. }
  62. // If not blank, set the java version passed to javadoc as -source
  63. Java_version *string
  64. // local files that are used within user customized droiddoc options.
  65. Arg_files []string `android:"path"`
  66. // user customized droiddoc args. Deprecated, use flags instead.
  67. // Available variables for substitution:
  68. //
  69. // $(location <label>): the path to the arg_files with name <label>
  70. // $$: a literal $
  71. Args *string
  72. // user customized droiddoc args. Not compatible with property args.
  73. // Available variables for substitution:
  74. //
  75. // $(location <label>): the path to the arg_files with name <label>
  76. // $$: a literal $
  77. Flags []string
  78. // names of the output files used in args that will be generated
  79. Out []string
  80. }
  81. type ApiToCheck struct {
  82. // path to the API txt file that the new API extracted from source code is checked
  83. // against. The path can be local to the module or from other module (via :module syntax).
  84. Api_file *string `android:"path"`
  85. // path to the API txt file that the new @removed API extractd from source code is
  86. // checked against. The path can be local to the module or from other module (via
  87. // :module syntax).
  88. Removed_api_file *string `android:"path"`
  89. // If not blank, path to the baseline txt file for approved API check violations.
  90. Baseline_file *string `android:"path"`
  91. // Arguments to the apicheck tool.
  92. Args *string
  93. }
  94. type DroiddocProperties struct {
  95. // directory relative to top of the source tree that contains doc templates files.
  96. Custom_template *string
  97. // directories under current module source which contains html/jd files.
  98. Html_dirs []string
  99. // set a value in the Clearsilver hdf namespace.
  100. Hdf []string
  101. // proofread file contains all of the text content of the javadocs concatenated into one file,
  102. // suitable for spell-checking and other goodness.
  103. Proofread_file *string
  104. // a todo file lists the program elements that are missing documentation.
  105. // At some point, this might be improved to show more warnings.
  106. Todo_file *string `android:"path"`
  107. // directory under current module source that provide additional resources (images).
  108. Resourcesdir *string
  109. // resources output directory under out/soong/.intermediates.
  110. Resourcesoutdir *string
  111. // index.html under current module will be copied to docs out dir, if not null.
  112. Static_doc_index_redirect *string `android:"path"`
  113. // source.properties under current module will be copied to docs out dir, if not null.
  114. Static_doc_properties *string `android:"path"`
  115. // a list of files under current module source dir which contains known tags in Java sources.
  116. // filegroup or genrule can be included within this property.
  117. Knowntags []string `android:"path"`
  118. // if set to true, generate docs through Dokka instead of Doclava.
  119. Dokka_enabled *bool
  120. // Compat config XML. Generates compat change documentation if set.
  121. Compat_config *string `android:"path"`
  122. }
  123. // Common flags passed down to build rule
  124. type droiddocBuilderFlags struct {
  125. bootClasspathArgs string
  126. classpathArgs string
  127. sourcepathArgs string
  128. dokkaClasspathArgs string
  129. aidlFlags string
  130. aidlDeps android.Paths
  131. doclavaStubsFlags string
  132. doclavaDocsFlags string
  133. postDoclavaCmds string
  134. }
  135. func InitDroiddocModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
  136. android.InitAndroidArchModule(module, hod, android.MultilibCommon)
  137. android.InitDefaultableModule(module)
  138. }
  139. func apiCheckEnabled(ctx android.ModuleContext, apiToCheck ApiToCheck, apiVersionTag string) bool {
  140. if ctx.Config().IsEnvTrue("WITHOUT_CHECK_API") {
  141. return false
  142. } else if String(apiToCheck.Api_file) != "" && String(apiToCheck.Removed_api_file) != "" {
  143. return true
  144. } else if String(apiToCheck.Api_file) != "" {
  145. panic("for " + apiVersionTag + " removed_api_file has to be non-empty!")
  146. } else if String(apiToCheck.Removed_api_file) != "" {
  147. panic("for " + apiVersionTag + " api_file has to be non-empty!")
  148. }
  149. return false
  150. }
  151. // Javadoc
  152. type Javadoc struct {
  153. android.ModuleBase
  154. android.DefaultableModuleBase
  155. properties JavadocProperties
  156. srcJars android.Paths
  157. srcFiles android.Paths
  158. sourcepaths android.Paths
  159. implicits android.Paths
  160. docZip android.WritablePath
  161. stubsSrcJar android.WritablePath
  162. }
  163. func (j *Javadoc) OutputFiles(tag string) (android.Paths, error) {
  164. switch tag {
  165. case "":
  166. return android.Paths{j.stubsSrcJar}, nil
  167. case ".docs.zip":
  168. return android.Paths{j.docZip}, nil
  169. default:
  170. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  171. }
  172. }
  173. // javadoc converts .java source files to documentation using javadoc.
  174. func JavadocFactory() android.Module {
  175. module := &Javadoc{}
  176. module.AddProperties(&module.properties)
  177. InitDroiddocModule(module, android.HostAndDeviceSupported)
  178. return module
  179. }
  180. // javadoc_host converts .java source files to documentation using javadoc.
  181. func JavadocHostFactory() android.Module {
  182. module := &Javadoc{}
  183. module.AddProperties(&module.properties)
  184. InitDroiddocModule(module, android.HostSupported)
  185. return module
  186. }
  187. var _ android.OutputFileProducer = (*Javadoc)(nil)
  188. func (j *Javadoc) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  189. return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
  190. }
  191. func (j *Javadoc) SystemModules() string {
  192. return proptools.String(j.properties.System_modules)
  193. }
  194. func (j *Javadoc) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  195. return j.SdkVersion(ctx)
  196. }
  197. func (j *Javadoc) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.SdkSpec {
  198. return j.SdkVersion(ctx)
  199. }
  200. func (j *Javadoc) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  201. return j.SdkVersion(ctx)
  202. }
  203. func (j *Javadoc) addDeps(ctx android.BottomUpMutatorContext) {
  204. if ctx.Device() {
  205. sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
  206. if sdkDep.useModule {
  207. ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
  208. ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
  209. ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
  210. ctx.AddVariationDependencies(nil, libTag, sdkDep.classpath...)
  211. }
  212. }
  213. ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
  214. }
  215. func (j *Javadoc) collectAidlFlags(ctx android.ModuleContext, deps deps) droiddocBuilderFlags {
  216. var flags droiddocBuilderFlags
  217. flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
  218. return flags
  219. }
  220. func (j *Javadoc) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
  221. aidlIncludeDirs android.Paths) (string, android.Paths) {
  222. aidlIncludes := android.PathsForModuleSrc(ctx, j.properties.Aidl.Local_include_dirs)
  223. aidlIncludes = append(aidlIncludes, android.PathsForSource(ctx, j.properties.Aidl.Include_dirs)...)
  224. var flags []string
  225. var deps android.Paths
  226. if aidlPreprocess.Valid() {
  227. flags = append(flags, "-p"+aidlPreprocess.String())
  228. deps = append(deps, aidlPreprocess.Path())
  229. } else {
  230. flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
  231. }
  232. flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
  233. flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
  234. if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
  235. flags = append(flags, "-I"+src.String())
  236. }
  237. return strings.Join(flags, " "), deps
  238. }
  239. // TODO: remove the duplication between this and the one in gen.go
  240. func (j *Javadoc) genSources(ctx android.ModuleContext, srcFiles android.Paths,
  241. flags droiddocBuilderFlags) android.Paths {
  242. outSrcFiles := make(android.Paths, 0, len(srcFiles))
  243. var aidlSrcs android.Paths
  244. aidlIncludeFlags := genAidlIncludeFlags(srcFiles)
  245. for _, srcFile := range srcFiles {
  246. switch srcFile.Ext() {
  247. case ".aidl":
  248. aidlSrcs = append(aidlSrcs, srcFile)
  249. case ".logtags":
  250. javaFile := genLogtags(ctx, srcFile)
  251. outSrcFiles = append(outSrcFiles, javaFile)
  252. default:
  253. outSrcFiles = append(outSrcFiles, srcFile)
  254. }
  255. }
  256. // Process all aidl files together to support sharding them into one or more rules that produce srcjars.
  257. if len(aidlSrcs) > 0 {
  258. srcJarFiles := genAidl(ctx, aidlSrcs, flags.aidlFlags+aidlIncludeFlags, nil, flags.aidlDeps)
  259. outSrcFiles = append(outSrcFiles, srcJarFiles...)
  260. }
  261. return outSrcFiles
  262. }
  263. func (j *Javadoc) collectDeps(ctx android.ModuleContext) deps {
  264. var deps deps
  265. sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
  266. if sdkDep.invalidVersion {
  267. ctx.AddMissingDependencies(sdkDep.bootclasspath)
  268. ctx.AddMissingDependencies(sdkDep.java9Classpath)
  269. } else if sdkDep.useFiles {
  270. deps.bootClasspath = append(deps.bootClasspath, sdkDep.jars...)
  271. deps.aidlPreprocess = sdkDep.aidl
  272. } else {
  273. deps.aidlPreprocess = sdkDep.aidl
  274. }
  275. ctx.VisitDirectDeps(func(module android.Module) {
  276. otherName := ctx.OtherModuleName(module)
  277. tag := ctx.OtherModuleDependencyTag(module)
  278. switch tag {
  279. case bootClasspathTag:
  280. if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
  281. dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
  282. deps.bootClasspath = append(deps.bootClasspath, dep.ImplementationJars...)
  283. } else if sm, ok := module.(SystemModulesProvider); ok {
  284. // A system modules dependency has been added to the bootclasspath
  285. // so add its libs to the bootclasspath.
  286. deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
  287. } else {
  288. panic(fmt.Errorf("unknown dependency %q for %q", otherName, ctx.ModuleName()))
  289. }
  290. case libTag:
  291. if dep, ok := module.(SdkLibraryDependency); ok {
  292. deps.classpath = append(deps.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
  293. } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
  294. dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
  295. deps.classpath = append(deps.classpath, dep.HeaderJars...)
  296. deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
  297. } else if dep, ok := module.(android.SourceFileProducer); ok {
  298. checkProducesJars(ctx, dep)
  299. deps.classpath = append(deps.classpath, dep.Srcs()...)
  300. } else {
  301. ctx.ModuleErrorf("depends on non-java module %q", otherName)
  302. }
  303. case java9LibTag:
  304. if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
  305. dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
  306. deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
  307. } else {
  308. ctx.ModuleErrorf("depends on non-java module %q", otherName)
  309. }
  310. case systemModulesTag:
  311. if deps.systemModules != nil {
  312. panic("Found two system module dependencies")
  313. }
  314. sm := module.(SystemModulesProvider)
  315. outputDir, outputDeps := sm.OutputDirAndDeps()
  316. deps.systemModules = &systemModules{outputDir, outputDeps}
  317. }
  318. })
  319. // do not pass exclude_srcs directly when expanding srcFiles since exclude_srcs
  320. // may contain filegroup or genrule.
  321. srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
  322. j.implicits = append(j.implicits, srcFiles...)
  323. filterByPackage := func(srcs []android.Path, filterPackages []string) []android.Path {
  324. if filterPackages == nil {
  325. return srcs
  326. }
  327. filtered := []android.Path{}
  328. for _, src := range srcs {
  329. if src.Ext() != ".java" {
  330. // Don't filter-out non-Java (=generated sources) by package names. This is not ideal,
  331. // but otherwise metalava emits stub sources having references to the generated AIDL classes
  332. // in filtered-out pacages (e.g. com.android.internal.*).
  333. // TODO(b/141149570) We need to fix this by introducing default private constructors or
  334. // fixing metalava to not emit constructors having references to unknown classes.
  335. filtered = append(filtered, src)
  336. continue
  337. }
  338. packageName := strings.ReplaceAll(filepath.Dir(src.Rel()), "/", ".")
  339. if android.HasAnyPrefix(packageName, filterPackages) {
  340. filtered = append(filtered, src)
  341. }
  342. }
  343. return filtered
  344. }
  345. srcFiles = filterByPackage(srcFiles, j.properties.Filter_packages)
  346. aidlFlags := j.collectAidlFlags(ctx, deps)
  347. srcFiles = j.genSources(ctx, srcFiles, aidlFlags)
  348. // srcs may depend on some genrule output.
  349. j.srcJars = srcFiles.FilterByExt(".srcjar")
  350. j.srcJars = append(j.srcJars, deps.srcJars...)
  351. j.srcFiles = srcFiles.FilterOutByExt(".srcjar")
  352. j.srcFiles = append(j.srcFiles, deps.srcs...)
  353. if len(j.srcFiles) > 0 {
  354. j.sourcepaths = android.PathsForModuleSrc(ctx, []string{"."})
  355. }
  356. return deps
  357. }
  358. func (j *Javadoc) expandArgs(ctx android.ModuleContext, cmd *android.RuleBuilderCommand) {
  359. var argFiles android.Paths
  360. argFilesMap := map[string]string{}
  361. argFileLabels := []string{}
  362. for _, label := range j.properties.Arg_files {
  363. var paths = android.PathsForModuleSrc(ctx, []string{label})
  364. if _, exists := argFilesMap[label]; !exists {
  365. argFilesMap[label] = strings.Join(cmd.PathsForInputs(paths), " ")
  366. argFileLabels = append(argFileLabels, label)
  367. argFiles = append(argFiles, paths...)
  368. } else {
  369. ctx.ModuleErrorf("multiple arg_files for %q, %q and %q",
  370. label, argFilesMap[label], paths)
  371. }
  372. }
  373. var argsPropertyName string
  374. flags := make([]string, 0)
  375. if j.properties.Args != nil && j.properties.Flags != nil {
  376. ctx.PropertyErrorf("args", "flags is set. Cannot set args")
  377. } else if args := proptools.String(j.properties.Args); args != "" {
  378. flags = append(flags, args)
  379. argsPropertyName = "args"
  380. } else {
  381. flags = append(flags, j.properties.Flags...)
  382. argsPropertyName = "flags"
  383. }
  384. for _, flag := range flags {
  385. expanded, err := android.Expand(flag, func(name string) (string, error) {
  386. if strings.HasPrefix(name, "location ") {
  387. label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
  388. if paths, ok := argFilesMap[label]; ok {
  389. return paths, nil
  390. } else {
  391. return "", fmt.Errorf("unknown location label %q, expecting one of %q",
  392. label, strings.Join(argFileLabels, ", "))
  393. }
  394. } else if name == "genDir" {
  395. return android.PathForModuleGen(ctx).String(), nil
  396. }
  397. return "", fmt.Errorf("unknown variable '$(%s)'", name)
  398. })
  399. if err != nil {
  400. ctx.PropertyErrorf(argsPropertyName, "%s", err.Error())
  401. }
  402. cmd.Flag(expanded)
  403. }
  404. cmd.Implicits(argFiles)
  405. }
  406. func (j *Javadoc) DepsMutator(ctx android.BottomUpMutatorContext) {
  407. j.addDeps(ctx)
  408. }
  409. func (j *Javadoc) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  410. deps := j.collectDeps(ctx)
  411. j.docZip = android.PathForModuleOut(ctx, ctx.ModuleName()+"-"+"docs.zip")
  412. outDir := android.PathForModuleOut(ctx, "out")
  413. srcJarDir := android.PathForModuleOut(ctx, "srcjars")
  414. j.stubsSrcJar = nil
  415. rule := android.NewRuleBuilder(pctx, ctx)
  416. rule.Command().Text("rm -rf").Text(outDir.String())
  417. rule.Command().Text("mkdir -p").Text(outDir.String())
  418. srcJarList := zipSyncCmd(ctx, rule, srcJarDir, j.srcJars)
  419. javaVersion := getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
  420. cmd := javadocSystemModulesCmd(ctx, rule, j.srcFiles, outDir, srcJarDir, srcJarList,
  421. deps.systemModules, deps.classpath, j.sourcepaths)
  422. cmd.FlagWithArg("-source ", javaVersion.String()).
  423. Flag("-J-Xmx1024m").
  424. Flag("-XDignore.symbol.file").
  425. Flag("-Xdoclint:none")
  426. j.expandArgs(ctx, cmd)
  427. rule.Command().
  428. BuiltTool("soong_zip").
  429. Flag("-write_if_changed").
  430. Flag("-d").
  431. FlagWithOutput("-o ", j.docZip).
  432. FlagWithArg("-C ", outDir.String()).
  433. FlagWithArg("-D ", outDir.String())
  434. rule.Restat()
  435. zipSyncCleanupCmd(rule, srcJarDir)
  436. rule.Build("javadoc", "javadoc")
  437. }
  438. // Droiddoc
  439. type Droiddoc struct {
  440. Javadoc
  441. properties DroiddocProperties
  442. }
  443. // droiddoc converts .java source files to documentation using doclava or dokka.
  444. func DroiddocFactory() android.Module {
  445. module := &Droiddoc{}
  446. module.AddProperties(&module.properties,
  447. &module.Javadoc.properties)
  448. InitDroiddocModule(module, android.HostAndDeviceSupported)
  449. return module
  450. }
  451. // droiddoc_host converts .java source files to documentation using doclava or dokka.
  452. func DroiddocHostFactory() android.Module {
  453. module := &Droiddoc{}
  454. module.AddProperties(&module.properties,
  455. &module.Javadoc.properties)
  456. InitDroiddocModule(module, android.HostSupported)
  457. return module
  458. }
  459. func (d *Droiddoc) OutputFiles(tag string) (android.Paths, error) {
  460. switch tag {
  461. case "", ".docs.zip":
  462. return android.Paths{d.Javadoc.docZip}, nil
  463. default:
  464. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  465. }
  466. }
  467. func (d *Droiddoc) DepsMutator(ctx android.BottomUpMutatorContext) {
  468. d.Javadoc.addDeps(ctx)
  469. if String(d.properties.Custom_template) != "" {
  470. ctx.AddDependency(ctx.Module(), droiddocTemplateTag, String(d.properties.Custom_template))
  471. }
  472. }
  473. func (d *Droiddoc) doclavaDocsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, docletPath classpath) {
  474. buildNumberFile := ctx.Config().BuildNumberFile(ctx)
  475. // Droiddoc always gets "-source 1.8" because it doesn't support 1.9 sources. For modules with 1.9
  476. // sources, droiddoc will get sources produced by metalava which will have already stripped out the
  477. // 1.9 language features.
  478. cmd.FlagWithArg("-source ", "1.8").
  479. Flag("-J-Xmx1600m").
  480. Flag("-J-XX:-OmitStackTraceInFastThrow").
  481. Flag("-XDignore.symbol.file").
  482. FlagWithArg("-doclet ", "com.google.doclava.Doclava").
  483. FlagWithInputList("-docletpath ", docletPath.Paths(), ":").
  484. FlagWithArg("-hdf page.build ", ctx.Config().BuildId()+"-$(cat "+buildNumberFile.String()+")").OrderOnly(buildNumberFile).
  485. FlagWithArg("-hdf page.now ", `"$(date -d @$(cat `+ctx.Config().Getenv("BUILD_DATETIME_FILE")+`) "+%d %b %Y %k:%M")" `)
  486. if String(d.properties.Custom_template) == "" {
  487. // TODO: This is almost always droiddoc-templates-sdk
  488. ctx.PropertyErrorf("custom_template", "must specify a template")
  489. }
  490. ctx.VisitDirectDepsWithTag(droiddocTemplateTag, func(m android.Module) {
  491. if t, ok := m.(*ExportedDroiddocDir); ok {
  492. cmd.FlagWithArg("-templatedir ", t.dir.String()).Implicits(t.deps)
  493. } else {
  494. ctx.PropertyErrorf("custom_template", "module %q is not a droiddoc_exported_dir", ctx.OtherModuleName(m))
  495. }
  496. })
  497. if len(d.properties.Html_dirs) > 0 {
  498. htmlDir := android.PathForModuleSrc(ctx, d.properties.Html_dirs[0])
  499. cmd.FlagWithArg("-htmldir ", htmlDir.String()).
  500. Implicits(android.PathsForModuleSrc(ctx, []string{filepath.Join(d.properties.Html_dirs[0], "**/*")}))
  501. }
  502. if len(d.properties.Html_dirs) > 1 {
  503. htmlDir2 := android.PathForModuleSrc(ctx, d.properties.Html_dirs[1])
  504. cmd.FlagWithArg("-htmldir2 ", htmlDir2.String()).
  505. Implicits(android.PathsForModuleSrc(ctx, []string{filepath.Join(d.properties.Html_dirs[1], "**/*")}))
  506. }
  507. if len(d.properties.Html_dirs) > 2 {
  508. ctx.PropertyErrorf("html_dirs", "Droiddoc only supports up to 2 html dirs")
  509. }
  510. knownTags := android.PathsForModuleSrc(ctx, d.properties.Knowntags)
  511. cmd.FlagForEachInput("-knowntags ", knownTags)
  512. cmd.FlagForEachArg("-hdf ", d.properties.Hdf)
  513. if String(d.properties.Proofread_file) != "" {
  514. proofreadFile := android.PathForModuleOut(ctx, String(d.properties.Proofread_file))
  515. cmd.FlagWithOutput("-proofread ", proofreadFile)
  516. }
  517. if String(d.properties.Todo_file) != "" {
  518. // tricky part:
  519. // we should not compute full path for todo_file through PathForModuleOut().
  520. // the non-standard doclet will get the full path relative to "-o".
  521. cmd.FlagWithArg("-todo ", String(d.properties.Todo_file)).
  522. ImplicitOutput(android.PathForModuleOut(ctx, String(d.properties.Todo_file)))
  523. }
  524. if String(d.properties.Resourcesdir) != "" {
  525. // TODO: should we add files under resourcesDir to the implicits? It seems that
  526. // resourcesDir is one sub dir of htmlDir
  527. resourcesDir := android.PathForModuleSrc(ctx, String(d.properties.Resourcesdir))
  528. cmd.FlagWithArg("-resourcesdir ", resourcesDir.String())
  529. }
  530. if String(d.properties.Resourcesoutdir) != "" {
  531. // TODO: it seems -resourceoutdir reference/android/images/ didn't get generated anywhere.
  532. cmd.FlagWithArg("-resourcesoutdir ", String(d.properties.Resourcesoutdir))
  533. }
  534. }
  535. func (d *Droiddoc) postDoclavaCmds(ctx android.ModuleContext, rule *android.RuleBuilder) {
  536. if String(d.properties.Static_doc_index_redirect) != "" {
  537. staticDocIndexRedirect := android.PathForModuleSrc(ctx, String(d.properties.Static_doc_index_redirect))
  538. rule.Command().Text("cp").
  539. Input(staticDocIndexRedirect).
  540. Output(android.PathForModuleOut(ctx, "out", "index.html"))
  541. }
  542. if String(d.properties.Static_doc_properties) != "" {
  543. staticDocProperties := android.PathForModuleSrc(ctx, String(d.properties.Static_doc_properties))
  544. rule.Command().Text("cp").
  545. Input(staticDocProperties).
  546. Output(android.PathForModuleOut(ctx, "out", "source.properties"))
  547. }
  548. }
  549. func javadocCmd(ctx android.ModuleContext, rule *android.RuleBuilder, srcs android.Paths,
  550. outDir, srcJarDir, srcJarList android.Path, sourcepaths android.Paths) *android.RuleBuilderCommand {
  551. cmd := rule.Command().
  552. BuiltTool("soong_javac_wrapper").Tool(config.JavadocCmd(ctx)).
  553. Flag(config.JavacVmFlags).
  554. FlagWithArg("-encoding ", "UTF-8").
  555. FlagWithRspFileInputList("@", android.PathForModuleOut(ctx, "javadoc.rsp"), srcs).
  556. FlagWithInput("@", srcJarList)
  557. // TODO(ccross): Remove this if- statement once we finish migration for all Doclava
  558. // based stubs generation.
  559. // In the future, all the docs generation depends on Metalava stubs (droidstubs) srcjar
  560. // dir. We need add the srcjar dir to -sourcepath arg, so that Javadoc can figure out
  561. // the correct package name base path.
  562. if len(sourcepaths) > 0 {
  563. cmd.FlagWithList("-sourcepath ", sourcepaths.Strings(), ":")
  564. } else {
  565. cmd.FlagWithArg("-sourcepath ", srcJarDir.String())
  566. }
  567. cmd.FlagWithArg("-d ", outDir.String()).
  568. Flag("-quiet")
  569. return cmd
  570. }
  571. func javadocSystemModulesCmd(ctx android.ModuleContext, rule *android.RuleBuilder, srcs android.Paths,
  572. outDir, srcJarDir, srcJarList android.Path, systemModules *systemModules,
  573. classpath classpath, sourcepaths android.Paths) *android.RuleBuilderCommand {
  574. cmd := javadocCmd(ctx, rule, srcs, outDir, srcJarDir, srcJarList, sourcepaths)
  575. flag, deps := systemModules.FormJavaSystemModulesPath(ctx.Device())
  576. cmd.Flag(flag).Implicits(deps)
  577. cmd.FlagWithArg("--patch-module ", "java.base=.")
  578. if len(classpath) > 0 {
  579. cmd.FlagWithInputList("-classpath ", classpath.Paths(), ":")
  580. }
  581. return cmd
  582. }
  583. func javadocBootclasspathCmd(ctx android.ModuleContext, rule *android.RuleBuilder, srcs android.Paths,
  584. outDir, srcJarDir, srcJarList android.Path, bootclasspath, classpath classpath,
  585. sourcepaths android.Paths) *android.RuleBuilderCommand {
  586. cmd := javadocCmd(ctx, rule, srcs, outDir, srcJarDir, srcJarList, sourcepaths)
  587. if len(bootclasspath) == 0 && ctx.Device() {
  588. // explicitly specify -bootclasspath "" if the bootclasspath is empty to
  589. // ensure java does not fall back to the default bootclasspath.
  590. cmd.FlagWithArg("-bootclasspath ", `""`)
  591. } else if len(bootclasspath) > 0 {
  592. cmd.FlagWithInputList("-bootclasspath ", bootclasspath.Paths(), ":")
  593. }
  594. if len(classpath) > 0 {
  595. cmd.FlagWithInputList("-classpath ", classpath.Paths(), ":")
  596. }
  597. return cmd
  598. }
  599. func dokkaCmd(ctx android.ModuleContext, rule *android.RuleBuilder,
  600. outDir, srcJarDir android.Path, bootclasspath, classpath classpath) *android.RuleBuilderCommand {
  601. // Dokka doesn't support bootClasspath, so combine these two classpath vars for Dokka.
  602. dokkaClasspath := append(bootclasspath.Paths(), classpath.Paths()...)
  603. return rule.Command().
  604. BuiltTool("dokka").
  605. Flag(config.JavacVmFlags).
  606. Flag(srcJarDir.String()).
  607. FlagWithInputList("-classpath ", dokkaClasspath, ":").
  608. FlagWithArg("-format ", "dac").
  609. FlagWithArg("-dacRoot ", "/reference/kotlin").
  610. FlagWithArg("-output ", outDir.String())
  611. }
  612. func (d *Droiddoc) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  613. deps := d.Javadoc.collectDeps(ctx)
  614. d.Javadoc.docZip = android.PathForModuleOut(ctx, ctx.ModuleName()+"-"+"docs.zip")
  615. jsilver := ctx.Config().HostJavaToolPath(ctx, "jsilver.jar")
  616. doclava := ctx.Config().HostJavaToolPath(ctx, "doclava.jar")
  617. outDir := android.PathForModuleOut(ctx, "out")
  618. srcJarDir := android.PathForModuleOut(ctx, "srcjars")
  619. rule := android.NewRuleBuilder(pctx, ctx)
  620. srcJarList := zipSyncCmd(ctx, rule, srcJarDir, d.Javadoc.srcJars)
  621. var cmd *android.RuleBuilderCommand
  622. if Bool(d.properties.Dokka_enabled) {
  623. cmd = dokkaCmd(ctx, rule, outDir, srcJarDir, deps.bootClasspath, deps.classpath)
  624. } else {
  625. cmd = javadocBootclasspathCmd(ctx, rule, d.Javadoc.srcFiles, outDir, srcJarDir, srcJarList,
  626. deps.bootClasspath, deps.classpath, d.Javadoc.sourcepaths)
  627. }
  628. d.expandArgs(ctx, cmd)
  629. if d.properties.Compat_config != nil {
  630. compatConfig := android.PathForModuleSrc(ctx, String(d.properties.Compat_config))
  631. cmd.FlagWithInput("-compatconfig ", compatConfig)
  632. }
  633. var desc string
  634. if Bool(d.properties.Dokka_enabled) {
  635. desc = "dokka"
  636. } else {
  637. d.doclavaDocsFlags(ctx, cmd, classpath{jsilver, doclava})
  638. for _, o := range d.Javadoc.properties.Out {
  639. cmd.ImplicitOutput(android.PathForModuleGen(ctx, o))
  640. }
  641. d.postDoclavaCmds(ctx, rule)
  642. desc = "doclava"
  643. }
  644. rule.Command().
  645. BuiltTool("soong_zip").
  646. Flag("-write_if_changed").
  647. Flag("-d").
  648. FlagWithOutput("-o ", d.docZip).
  649. FlagWithArg("-C ", outDir.String()).
  650. FlagWithArg("-D ", outDir.String())
  651. rule.Restat()
  652. zipSyncCleanupCmd(rule, srcJarDir)
  653. rule.Build("javadoc", desc)
  654. }
  655. // Exported Droiddoc Directory
  656. var droiddocTemplateTag = dependencyTag{name: "droiddoc-template"}
  657. type ExportedDroiddocDirProperties struct {
  658. // path to the directory containing Droiddoc related files.
  659. Path *string
  660. }
  661. type ExportedDroiddocDir struct {
  662. android.ModuleBase
  663. properties ExportedDroiddocDirProperties
  664. deps android.Paths
  665. dir android.Path
  666. }
  667. // droiddoc_exported_dir exports a directory of html templates or nullability annotations for use by doclava.
  668. func ExportedDroiddocDirFactory() android.Module {
  669. module := &ExportedDroiddocDir{}
  670. module.AddProperties(&module.properties)
  671. android.InitAndroidModule(module)
  672. return module
  673. }
  674. func (d *ExportedDroiddocDir) DepsMutator(android.BottomUpMutatorContext) {}
  675. func (d *ExportedDroiddocDir) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  676. path := String(d.properties.Path)
  677. d.dir = android.PathForModuleSrc(ctx, path)
  678. d.deps = android.PathsForModuleSrc(ctx, []string{filepath.Join(path, "**/*")})
  679. }
  680. // Defaults
  681. type DocDefaults struct {
  682. android.ModuleBase
  683. android.DefaultsModuleBase
  684. }
  685. func DocDefaultsFactory() android.Module {
  686. module := &DocDefaults{}
  687. module.AddProperties(
  688. &JavadocProperties{},
  689. &DroiddocProperties{},
  690. )
  691. android.InitDefaultsModule(module)
  692. return module
  693. }
  694. func zipSyncCmd(ctx android.ModuleContext, rule *android.RuleBuilder,
  695. srcJarDir android.ModuleOutPath, srcJars android.Paths) android.OutputPath {
  696. cmd := rule.Command()
  697. cmd.Text("rm -rf").Text(cmd.PathForOutput(srcJarDir))
  698. cmd = rule.Command()
  699. cmd.Text("mkdir -p").Text(cmd.PathForOutput(srcJarDir))
  700. srcJarList := srcJarDir.Join(ctx, "list")
  701. rule.Temporary(srcJarList)
  702. cmd = rule.Command()
  703. cmd.BuiltTool("zipsync").
  704. FlagWithArg("-d ", cmd.PathForOutput(srcJarDir)).
  705. FlagWithOutput("-l ", srcJarList).
  706. FlagWithArg("-f ", `"*.java"`).
  707. Inputs(srcJars)
  708. return srcJarList
  709. }
  710. func zipSyncCleanupCmd(rule *android.RuleBuilder, srcJarDir android.ModuleOutPath) {
  711. rule.Command().Text("rm -rf").Text(srcJarDir.String())
  712. }