Debian Codegraph @

R/renvignore.R

raw
1
2 # given a path within a project, read all relevant ignore files
3 # and generate a pattern that can be used to filter file results
4 renv_renvignore_pattern <- function(path = getwd(), root = path) {
5
6 if (is.null(root))
7 return(NULL)
8
9 stopifnot(
10 renv_path_absolute(path),
11 renv_path_absolute(root)
12 )
13
14 # prepare ignores
15 ignores <- stack()
16
17 # read ignore files
18 parent <- path
19 repeat {
20
21 # attempt to read either .renvignore or .gitignore
22 for (file in c(".renvignore", ".gitignore")) {
23 candidate <- file.path(parent, file)
24 if (file.exists(candidate)) {
25 contents <- readLines(candidate, warn = FALSE)
26 parsed <- renv_renvignore_parse(contents, parent)
27 if (length(parsed))
28 ignores$push(parsed)
29 break
30 }
31 }
32
33 # stop once we've hit the project root
34 if (parent == root || dirname(parent) == parent)
35 break
36
37 parent <- dirname(parent)
38
39 }
40
41 # collect patterns read
42 patterns <- ignores$data()
43
44 # separate exclusions, exclusions
45 include <- unlist(extract(patterns, "include"))
46 exclude <- unlist(extract(patterns, "exclude"))
47
48 # allow for inclusion / exclusion via option
49 # (primarily intended for internal use with packrat)
50 include <- c(include, renv_renvignore_pattern_extra("include", root))
51 exclude <- c(exclude, renv_renvignore_pattern_extra("exclude", root))
52
53 # ignore hidden directories by default
54 exclude <- c("/[.][^/]*/$", exclude)
55
56 list(include = include, exclude = exclude)
57
58 }
59
60 renv_renvignore_envir <- function(profile) {
61
62 envir <- new.env(parent = emptyenv())
63
64 # functions which we want to make available in .renvignore
65 envir[["c"]] <- base::c
66 envir[["list"]] <- base::list
67 envir[["%in%"]] <- base::`%in%`
68 envir[["if"]] <- base::`if`
69 envir[["=="]] <- base::`==`
70
71 # also add the profile
72 envir[["profile"]] <- profile
73 envir
74
75 }
76
77 renv_renvignore_filter <- function(contents) {
78
79 profile <- renv_profile_get() %||% "default"
80
81 # look for commented lines
82 matches <- which(startsWith(contents, "#|"))
83 if (length(matches) == 0L)
84 return(contents)
85
86 # make evaluation environment up-front if needed
87 envir <- renv_renvignore_envir(profile)
88
89 # build ranges
90 starts <- c(1L, matches)
91 ends <- c(matches - 1L, length(contents))
92 ranges <- .mapply(c, list(starts, ends), NULL)
93
94 # for each range, check if the ignore rule applies
95 # (the first range always applies by default)
96 keep <- rep.int(TRUE, length(ranges))
97 for (i in 2:length(ranges)) {
98
99 # pull out code from header
100 start <- ranges[[i]][[1L]]
101 header <- substring(contents[start], 3L)
102 code <- parse(text = header, keep.source = FALSE)[[1L]]
103
104 # if it's a symbol or a string, match against current profile
105 if (is.symbol(code) || is.character(code)) {
106 keep[[i]] <- as.character(code) %in% profile
107 next
108 }
109
110 # if it's code, evaluate it within a safe environment
111 if (is.call(code)) {
112 keep[[i]] <- eval(code, envir = new.env(parent = envir))
113 next
114 }
115
116 }
117
118 # now pull out the sections which apply
119 sections <- map(ranges[keep], function(range) {
120 contents[range[[1L]]:range[[2L]]]
121 })
122
123 unlist(sections, use.names = FALSE)
124
125 }
126
127 # reads a .gitignore / .renvignore file, and translates the associated
128 # entries into PCREs which can be combined and used during directory traversal
129 renv_renvignore_parse <- function(contents, prefix = "") {
130
131 # filter .renvignore contents based on profile
132 contents <- renv_renvignore_filter(contents)
133
134 # read the ignore entries
135 contents <- grep("^\\s*(?:#|$)", contents, value = TRUE, invert = TRUE)
136 if (empty(contents))
137 return(list())
138
139 # split into regions based on profile comments
140
141 # split into inclusion, exclusion patterns
142 negate <- substring(contents, 1L, 1L) == "!"
143 exclude <- contents[!negate]
144 include <- substring(contents[negate], 2L)
145
146 # For include rules, if we're explicitly including a file within
147 # a sub-directory, then we need to force all parent directories
148 # to also be included. In other words, a rule like:
149 #
150 # !a/b/c
151 #
152 # needs to be implicitly treated like
153 #
154 # !/a
155 # !/a/b
156 # !/a/b/c
157 #
158 # so we perform that transformation here.
159 #
160 # Note that this isn't perfect; for example, with the .gitignore file
161 #
162 # dir
163 # !dir/matched
164 #
165 # The exclusion of 'dir' will take precedence, and dir/matched won't
166 # get a chance to apply.
167 expanded <- map(include, function(rule) {
168
169 # check for slashes; leave unslashed rules alone
170 idx <- gregexpr("(?:/|$)", rule, perl = TRUE)[[1L]]
171 if (length(idx) == 1L)
172 return(rule)
173
174 # otherwise, split into multiple rules for each sub-directory
175 gsub("^/*", "/", substring(rule, 1L, idx))
176
177 })
178
179 # collapse back into a list
180 include <- unique(unlist(expanded))
181
182 # parse patterns separately
183 list(
184 exclude = renv_renvignore_parse_impl(exclude, prefix),
185 include = renv_renvignore_parse_impl(include, prefix)
186 )
187
188 }
189
190 renv_renvignore_parse_impl <- function(entries, prefix = "") {
191
192 # check for empty entries list
193 if (empty(entries))
194 return(character())
195
196 # remove trailing whitespace
197 entries <- gsub("\\s+$", "", entries)
198
199 # entries without a slash (other than a trailing one) should match in tree
200 noslash <- grep("/", gsub("/*$", "", entries), fixed = TRUE, invert = TRUE)
201 entries[noslash] <- paste("**", entries[noslash], sep = "/")
202
203 # remove a leading slash (avoid double-slashing)
204 entries <- gsub("^/+", "", entries)
205
206 # save any '**' entries seen
207 entries <- gsub("**/", "\001", entries, fixed = TRUE)
208 entries <- gsub("/**", "\002", entries, fixed = TRUE)
209
210 # transform '*' and '?'
211 entries <- gsub("*", "\\E[^/]*\\Q", entries, fixed = TRUE)
212 entries <- gsub("?", "\\E[^/]\\Q", entries, fixed = TRUE)
213
214 # restore '**' entries
215 entries <- gsub("\001", "\\E(?:.*/)?\\Q", entries, fixed = TRUE)
216 entries <- gsub("\002", "/\\E.*\\Q", entries, fixed = TRUE)
217
218 # if we don't have a trailing slash, then we can match both files and dirs
219 noslash <- grep("/$", entries, invert = TRUE)
220 entries[noslash] <- paste0(entries[noslash], "\\E(?:/)?\\Q")
221
222 # enclose in \\Q \\E to ensure e.g. plain '.' are not treated
223 # as regex characters
224 entries <- sprintf("\\Q%s\\E$", entries)
225
226 # prepend prefix
227 entries <- sprintf("^\\Q%s/\\E%s", prefix, entries)
228
229 # remove \\Q\\E, \\E\\Q
230 entries <- gsub("\\Q\\E", "", entries, fixed = TRUE)
231 entries <- gsub("\\E\\Q", "", entries, fixed = TRUE)
232
233 # all done!
234 entries
235
236 }
237
238 renv_renvignore_exec <- function(path, root, children) {
239
240 # the root directory is always included
241 if (identical(root, children))
242 return(FALSE)
243
244 # compute exclusion patterns
245 patterns <- renv_renvignore_pattern(path, root)
246
247 # if we have no patterns, then we're not excluding anything
248 if (empty(patterns) || empty(patterns$exclude))
249 return(logical(length(children)))
250
251 # append slashes to files which are directories
252 info <- renv_file_info(children)
253 dirs <- info$isdir %in% TRUE
254 children[dirs] <- paste0(children[dirs], "/")
255
256 # get the entries that need to be excluded
257 excludes <- logical(length = length(children))
258 for (pattern in patterns$exclude)
259 if (nzchar(pattern))
260 excludes <- excludes | grepl(pattern, children, perl = TRUE)
261
262 if (length(patterns$include)) {
263
264 # check for entries that should be explicitly included
265 # (note that these override any excludes)
266 includes <- logical(length = length(children))
267 for (pattern in patterns$include)
268 if (nzchar(pattern))
269 includes <- includes | grepl(pattern, children, perl = TRUE)
270
271 # unset those excludes
272 excludes[includes] <- FALSE
273
274 }
275
276 # return vector of excludes
277 excludes
278
279 }
280
281 renv_renvignore_pattern_extra <- function(key, root) {
282
283 # check for value from option
284 optname <- paste("renv.renvignore", key, sep = ".")
285 patterns <- getOption(optname)
286 if (is.null(patterns))
287 return(NULL)
288
289 # should we use the pattern as-is?
290 asis <- attr(patterns, "asis", exact = TRUE)
291 if (identical(asis, TRUE))
292 return(patterns)
293
294 # otherwise, process it as an .renvignore-style ignore
295 root <- attr(patterns, "root", exact = TRUE) %||% root
296 patterns <- renv_renvignore_parse(patterns, root)
297 patterns[[key]]
298
299 }
300
301 renv_renvignore_create <- function(paths,
302 create = FALSE,
303 contents = "*")
304 {
305 for (path in paths) {
306 if (file.exists(path)) {
307 ignorefile <- file.path(path, ".renvignore")
308 if (!file.exists(ignorefile))
309 writeLines(contents, con = ignorefile)
310 }
311 }
312 }
313