-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathbuild.R
225 lines (217 loc) · 8.84 KB
/
build.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#' Roxygenize a package, clean up and build/check the package
#'
#' After the source package is roxygenized, this function will build the
#' package. Optionally it also installs or checks the package, reformats the
#' code in the usage and examples sections. Note \code{\link{rab}} is an alias
#' of \code{\link{roxygen_and_build}}.
#' @param pkg the root directory of the source package
#' @param build whether to build the package
#' @param build.opts options to be passed to \command{R CMD build}
#' @param install whether to install the package
#' @param install.opts options to be passed to \command{R CMD INSTALL}
#' @param check whether to check the package
#' @param check.opts options to check the package (e.g. \code{"--no-examples"})
#' @param remove.check whether to remove the directory generated by \command{R
#' CMD check}
#' @param reformat whether to reformat the usage and examples code; see
#' \code{\link{reformat_code}}
#' @param before an R expression to be evaluated under the package root
#' directory before the package is roxygenized and built
#' @param ... other arguments passed to \code{\link[roxygen2]{roxygenize}}
#' @return \code{NULL}
#' @author Yihui Xie <\url{http://yihui.name}>
#' @rdname roxygen_and_build
#' @importFrom roxygen2 roxygenize
#' @import utils
#' @export
#' @examples \dontrun{
#' roxygen_and_build("Rd2roxygen", install = TRUE)
#' ## or simply
#' rab('Rd2roxygen', install = TRUE)
#' }
roxygen_and_build = function(
pkg, build = TRUE, build.opts = '--no-manual',
install = FALSE, install.opts = if (build) '' else '--with-keep.source',
check = FALSE, check.opts = '--as-cran --no-manual', remove.check = TRUE,
reformat = TRUE, before = NULL, ...
) {
do.call(library, list('methods'))
if (missing(pkg)) pkg = head(commandArgs(TRUE), 1)
if (length(pkg) != 1) stop('The package directory must be one character string')
in_dir(pkg, before)
roxygenize(pkg, ...)
if (reformat) {
message('Reformatting usage and examples')
rd.list = list.files(
file.path(pkg, 'man'), '.*\\.Rd$', all.files = TRUE, full.names = TRUE
)
for (f in rd.list) reformat_code(f)
}
desc = file.path(pkg, 'DESCRIPTION')
pv = read.dcf(desc, fields = c('Package', 'Version'))
# delete existing tarballs
unlink(sprintf('%s_*.tar.gz', pv[1, 1]))
if (build) {
system(sprintf('%s CMD build %s %s', Rbin(), build.opts, pkg))
}
res = sprintf('%s_%s.tar.gz', pv[1, 1], pv[1, 2])
if (install) {
if (!build) res = pkg
system(sprintf('%s CMD INSTALL %s %s ', Rbin(), install.opts, res))
# generate Rd for objects imported and exported from other packages
importRd(pkg, pv[1, 1])
}
if (check) {
if (!build) stop('You must build the source package before running R CMD check')
if ((system(sprintf('%s CMD check %s %s', Rbin(), res, check.opts)) == 0) &&
remove.check) unlink(sprintf('%s.Rcheck', pv[1, 1]), TRUE)
}
}
#' @rdname roxygen_and_build
#' @export
rab = roxygen_and_build
#' Format the code in the usage and examples sections
#'
#' The function \code{\link[formatR]{tidy_source}} in the \pkg{formatR} package
#' is used to polish the Rd files generated by \pkg{roxygen2} in the usage and
#' examples sections.
#' @param path the path of the Rd file
#' @param ... other arguments passed to \code{tidy_source}
#' @return \code{NULL}; as a side effect, the original Rd file will be updated
#' @export
#' @author Yihui Xie <\url{http://yihui.name}>
#' @seealso \code{\link[formatR]{tidy_source}}
#' @note If the usage or examples code is not syntactically correct, it will not
#' be reformatted and a message will be printed on screen. One possible
#' situation is the percent symbol \code{\%}, which should be escaped even in
#' the examples code (cf Writing R Extensions), and this can make the code
#' syntactically incorrect, e.g. \code{a \%in\% b} should be \code{a
#' \\\%in\\\% b} but the latter is not valid R code. Anyway, this function
#' will try to unescape the percent symbols before reformating the code, then
#' escape them.
#' @examples
#' rd.file = system.file('examples', 'reformat_code_demo.Rd', package = 'Rd2roxygen')
#' file.copy(rd.file, tempdir())
#' fmt.file = file.path(tempdir(), 'reformat_code_demo.Rd')
#'
#' file.show(fmt.file) ## show the raw Rd
#'
#' reformat_code(fmt.file)
#' file.show(fmt.file) ## the formatted Rd
reformat_code = function(path, ...) {
rd = readLines(path)
tags = tags_possible
if (length(idx0 <- grep('^\\\\examples\\{', rd))) {
# tags after \examples?
idx1 = grep(tags, rd)
if (length(idx1) && any(idx1 > idx0))
idx1 = min(idx1[idx1 > idx0]) - 1 else idx1 = tail(grep('\\}$', rd), 1)
rd = tidy_examples(rd, idx0, idx1, ..., path = path)
}
if (length(idx0 <- grep('^\\\\usage\\{', rd))) {
idx1 = grep(tags, rd)
if (length(idx1) && any(idx1 > idx0))
idx1 = min(idx1[idx1 > idx0]) - 1 else idx1 = length(rd)
tmp = rd[idx0:idx1]
tmp[1] = sub('^\\\\usage\\{', '', tmp[1])
nn = length(tmp)
tmp[nn] = sub('\\}$', '', tmp[nn])
txt = gsub('\\%', '%', tmp, fixed = TRUE) # will escape % later
txt = gsub('\\\\method\\{([^\\{]+)\\}\\{([^\\{]+)\\}', '`method@\\1@\\2`', txt) # S3
txt = tidy_code(txt, ...)
if (!inherits(txt, 'try-error')) {
txt = gsub('`method@([^@]+)@([^`]+)`', '\\\\method{\\1}{\\2}', txt) # restore S3
txt = gsub('(^|[^\\])%', '\\1\\\\%', txt)
if (txt[1] == '') txt = txt[-1]
if (txt[length(txt)] == '') txt = txt[-length(txt)]
txt = sprintf('\\usage{\n%s\n}', paste(txt, collapse = '\n'))
rd[idx0] = txt
if (idx1 > idx0) rd = rd[-((idx0 + 1):idx1)]
} else {
message('(!) failed to reformat usage code in ', path)
message(paste(' ', tmp, collapse = '\n'))
}
}
writeLines(strip_white(rd), path)
flush.console()
}
# strip beginning and trailing white spaces
strip_white = function(x) gsub('^\\s+|\\s+$', '', paste(x, collapse = '\n'))
# possible tags after \example{} or \usage{}
tags_possible = sprintf('^\\\\(%s)\\{', paste(c(
'docType', 'name', 'alias', 'title', 'format', 'source', 'usage', 'arguments',
'value', 'description', 'details', 'note', 'section', 'examples', 'author',
'references', 'seealso', 'concept', 'keyword', 'subsection'
), collapse = '|'))
tidy_code = function(code, ...) {
res = try(tidy_source(text = code, output = FALSE, width.cutoff = 80, ...)$text.tidy)
if (inherits(res, 'try-error')) return(res)
i = 1
# R CMD check used to require code width to be less than 90
while (any(nchar(unlist(strsplit(res, '\n'))) >= 90) && i <= 40) {
res = tidy_source(text = code, output = FALSE, width.cutoff = 90 - i, ...)$text.tidy
i = i + 1
}
if (i > 40) code else res
}
#' Generate R doc for functions imported from other packages and re-exported
#'
#' This function searches for exported functions in a package that are not
#' really created in this package, and generate documentation for them so that R
#' CMD check will not complain about the missing documentation for exported
#' functions.
#' @param path the path to the source package
#' @param package the package name
#' @noRd
importRd = function(path, package) {
escape = getFromNamespace('escape.character', 'roxygen2')
import = getNamespaceImports(package); import$base = NULL
pkgs = .packages(TRUE)
link = lapply(getNamespaceExports(package), function(name) {
fun = getExportedValue(package, name)
pkg = if (is.function(fun)) {
packageName(environment(fun))
} else {
which_package(name, import)
}
if (is.null(pkg) || pkg == package || !(pkg %in% pkgs)) return()
# if name is not exported there, you have to document it by yourself
if (!(name %in% getNamespaceExports(pkg))) return()
name = as.character(escape(name))
c(
package = pkg, name = name,
link = sprintf('\\code{\\link[%s:%s]{%s}}', pkg, name, name)
)
})
link = do.call(rbind, link)
if (NROW(link) == 0) return()
link = link[order(link[, 'package'], link[, 'name']), , drop = FALSE]
alias = sprintf('\\alias{%s}', link[, 'name'])
link = sapply(split(link[, 'link'], link[, 'package']), paste, collapse = ', ')
doc = c(
sprintf('\\name{%s-imports}', package),
alias,
'\\docType{import}',
'\\title{Objects imported from other packages}',
'\\description{',
'These objects are imported from other packages. Follow the links to their documentation.',
'\\describe{',
sprintf(' \\item{%s}{%s}', names(link), link),
'}}'
)
Rd = file.path(path, 'man', sprintf('%s-imports.Rd', package))
if (file.exists(Rd) && !any(readLines(Rd) == '\\docType{import}')) {
warning(
'The Rd file ', Rd, ' already exists. It seems I should not overwrite it. ',
'You may want to manually save the Rd below:', immediate. = TRUE
)
cat(doc, sep = '\n')
return()
}
writeLines(doc, Rd)
}
which_package = function(name, exports) {
for (i in names(exports)) {
if (name %in% exports[[i]]) return(i)
}
}