-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.R
More file actions
2101 lines (1869 loc) · 70 KB
/
Copy pathutils.R
File metadata and controls
2101 lines (1869 loc) · 70 KB
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# File src/library/tools/R/utils.R
# Part of the R package, https://www.R-project.org
#
# Copyright (C) 1995-2016 The R Core Team
#
# 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.
#
# A copy of the GNU General Public License is available at
# https://www.R-project.org/Licenses/
### * File utilities.
### ** file_ext
file_ext <-
function(x)
{
## Return the file extensions.
## (Only purely alphanumeric extensions are recognized.)
pos <- regexpr("\\.([[:alnum:]]+)$", x)
ifelse(pos > -1L, substring(x, pos + 1L), "")
}
### ** file_path_as_absolute
file_path_as_absolute <-
function(x)
{
## Turn a possibly relative file path absolute, performing tilde
## expansion if necessary.
if(length(x) != 1L)
stop("'x' must be a single character string")
if(!file.exists(epath <- path.expand(x)))
stop(gettextf("file '%s' does not exist", x),
domain = NA)
normalizePath(epath, "/", TRUE)
}
### ** file_path_sans_ext
file_path_sans_ext <-
function(x, compression = FALSE)
{
## Return the file paths without extensions.
## (Only purely alphanumeric extensions are recognized.)
if(compression)
x <- sub("[.](gz|bz2|xz)$", "", x)
sub("([^.]+)\\.[[:alnum:]]+$", "\\1", x)
}
### ** file_test
## exported/documented copy is in utils.
file_test <-
function(op, x, y)
{
## Provide shell-style '-f', '-d', '-x', '-nt' and '-ot' tests.
## Note that file.exists() only tests existence ('test -e' on some
## systems), and that our '-f' tests for existence and not being a
## directory (the GNU variant tests for being a regular file).
## Note: vectorized in x and y.
switch(op,
"-f" = !is.na(isdir <- file.info(x, extra_cols = FALSE)$isdir) & !isdir,
"-d" = dir.exists(x),
"-nt" = (!is.na(mt.x <- file.mtime(x))
& !is.na(mt.y <- file.mtime(y))
& (mt.x > mt.y)),
"-ot" = (!is.na(mt.x <- file.mtime(x))
& !is.na(mt.y <- file.mtime(y))
& (mt.x < mt.y)),
"-x" = (file.access(x, 1L) == 0L),
stop(gettextf("test '%s' is not available", op),
domain = NA))
}
### ** list_files_with_exts
list_files_with_exts <-
function(dir, exts, all.files = FALSE, full.names = TRUE)
{
## Return the paths or names of the files in @code{dir} with
## extension in @code{exts}.
## Might be in a zipped dir on Windows.
if(file.exists(file.path(dir, "filelist")) &&
any(file.exists(file.path(dir, c("Rdata.zip", "Rex.zip", "Rhelp.zip")))))
{
files <- readLines(file.path(dir, "filelist"))
if(!all.files)
files <- grep("^[^.]", files, value = TRUE)
} else {
files <- list.files(dir, all.files = all.files)
}
## does not cope with exts with '.' in.
## files <- files[sub(".*\\.", "", files) %in% exts]
patt <- paste0("\\.(", paste(exts, collapse="|"), ")$")
files <- grep(patt, files, value = TRUE)
if(full.names)
files <- if(length(files))
file.path(dir, files)
else
character()
files
}
### ** list_files_with_type
list_files_with_type <-
function(dir, type, all.files = FALSE, full.names = TRUE,
OS_subdirs = .OStype())
{
## Return a character vector with the paths of the files in
## @code{dir} of type @code{type} (as in .make_file_exts()).
## When listing R code and documentation files, files in OS-specific
## subdirectories are included (if present) according to the value
## of @code{OS_subdirs}.
exts <- .make_file_exts(type)
files <-
list_files_with_exts(dir, exts, all.files = all.files,
full.names = full.names)
if(type %in% c("code", "docs")) {
for(os in OS_subdirs) {
os_dir <- file.path(dir, os)
if(dir.exists(os_dir)) {
os_files <- list_files_with_exts(os_dir, exts,
all.files = all.files,
full.names = FALSE)
os_files <- file.path(if(full.names) os_dir else os,
os_files)
files <- c(files, os_files)
}
}
}
## avoid ranges since they depend on the collation order in the locale.
## in particular, Estonian sorts Z after S.
if(type %in% c("code", "docs")) { # only certain filenames are valid.
files <- files[grep("^[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789]", basename(files))]
}
if(type %in% "demo") { # only certain filenames are valid.
files <- files[grep("^[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]", basename(files))]
}
files
}
### ** reQuote
## <FIXME>
## Move into base eventually ...
reQuote <-
function(x)
{
escape <- function(s) paste0("\\", s)
re <- "[.*?+^$\\[]"
m <- gregexpr(re, x)
regmatches(x, m) <- lapply(regmatches(x, m), escape)
x
}
## </FIXME>
### ** showNonASCII
showNonASCII <-
function(x)
{
## All that is needed here is an 8-bit encoding that includes ASCII.
## The only one we guarantee to exist is 'latin1'.
## The default sub=NA is faster, but on some platforms
## some characters used just to lose their accents, so two tests.
asc <- iconv(x, "latin1", "ASCII")
ind <- is.na(asc) | asc != x
if(any(ind))
message(paste0(which(ind), ": ",
iconv(x[ind], "latin1", "ASCII", sub = "byte"),
collapse = "\n"), domain = NA)
invisible(x[ind])
}
showNonASCIIfile <-
function(file)
showNonASCII(readLines(file, warn = FALSE))
### * Text utilities.
### ** delimMatch
delimMatch <-
function(x, delim = c("{", "}"), syntax = "Rd")
{
if(!is.character(x))
stop("argument 'x' must be a character vector")
## FIXME: bytes or chars?
if((length(delim) != 2L) || any(nchar(delim) != 1L))
stop("argument 'delim' must specify two characters")
if(syntax != "Rd")
stop("only Rd syntax is currently supported")
.Call(delim_match, x, delim)
}
### * LaTeX utilities
### ** texi2pdf
texi2pdf <-
function(file, clean = FALSE, quiet = TRUE,
texi2dvi = getOption("texi2dvi"),
texinputs = NULL, index = TRUE)
texi2dvi(file = file, pdf = TRUE, clean = clean, quiet = quiet,
texi2dvi = texi2dvi, texinputs = texinputs, index = index)
### ** texi2dvi
texi2dvi <-
function(file, pdf = FALSE, clean = FALSE, quiet = TRUE,
texi2dvi = getOption("texi2dvi"),
texinputs = NULL, index = TRUE)
{
if (clean) pre_files <- list.files(all.files = TRUE)
do_cleanup <- function(clean)
if(clean) {
## output file will be created in the current directory
out_file <- paste(basename(file_path_sans_ext(file)),
if(pdf) "pdf" else "dvi", sep = ".")
files <- setdiff(list.files(all.files = TRUE),
c(".", "..", out_file, pre_files))
file.remove(files)
}
## Run texi2dvi on a latex file, or emulate it.
if(identical(texi2dvi, "emulation")) texi2dvi <- ""
else {
if(is.null(texi2dvi) || !nzchar(texi2dvi) || texi2dvi == "texi2dvi")
texi2dvi <- Sys.which("texi2dvi")
if(.Platform$OS.type == "windows" && !nzchar(texi2dvi))
texi2dvi <- Sys.which("texify")
}
envSep <- .Platform$path.sep
texinputs0 <- texinputs
Rtexmf <- file.path(R.home("share"), "texmf")
Rtexinputs <- file.path(Rtexmf, "tex", "latex")
## "" forces use of default paths.
texinputs <- paste(c(texinputs0, Rtexinputs, ""),
collapse = envSep)
## not clear if this is needed, but works
if(.Platform$OS.type == "windows")
texinputs <- gsub("\\", "/", texinputs, fixed = TRUE)
Rbibinputs <- file.path(Rtexmf, "bibtex", "bib")
bibinputs <- paste(c(texinputs0, Rbibinputs, ""),
collapse = envSep)
Rbstinputs <- file.path(Rtexmf, "bibtex", "bst")
bstinputs <- paste(c(texinputs0, Rbstinputs, ""),
collapse = envSep)
otexinputs <- Sys.getenv("TEXINPUTS", unset = NA_character_)
if(is.na(otexinputs)) {
on.exit(Sys.unsetenv("TEXINPUTS"))
otexinputs <- "."
} else on.exit(Sys.setenv(TEXINPUTS = otexinputs))
Sys.setenv(TEXINPUTS = paste(otexinputs, texinputs, sep = envSep))
obibinputs <- Sys.getenv("BIBINPUTS", unset = NA_character_)
if(is.na(obibinputs)) {
on.exit(Sys.unsetenv("BIBINPUTS"), add = TRUE)
obibinputs <- "."
} else on.exit(Sys.setenv(BIBINPUTS = obibinputs, add = TRUE))
Sys.setenv(BIBINPUTS = paste(obibinputs, bibinputs, sep = envSep))
obstinputs <- Sys.getenv("BSTINPUTS", unset = NA_character_)
if(is.na(obstinputs)) {
on.exit(Sys.unsetenv("BSTINPUTS"), add = TRUE)
obstinputs <- "."
} else on.exit(Sys.setenv(BSTINPUTS = obstinputs), add = TRUE)
Sys.setenv(BSTINPUTS = paste(obstinputs, bstinputs, sep = envSep))
if(index && nzchar(texi2dvi) && .Platform$OS.type != "windows") {
## switch off the use of texindy in texi2dvi >= 1.157
Sys.setenv(TEXINDY = "false")
on.exit(Sys.unsetenv("TEXINDY"), add = TRUE)
opt_pdf <- if(pdf) "--pdf" else ""
opt_quiet <- if(quiet) "--quiet" else ""
opt_extra <- ""
out <- .system_with_capture(texi2dvi, "--help")
if(length(grep("--no-line-error", out$stdout)))
opt_extra <- "--no-line-error"
## (Maybe change eventually: the current heuristics for finding
## error messages in log files should work for both regular and
## file line error indicators.)
## This is present in texinfo after late 2009, so really >= 5.0.
if(any(grepl("--max-iterations=N", out$stdout)))
opt_extra <- c(opt_extra, "--max-iterations=20")
## and work around a bug in texi2dvi
## https://stat.ethz.ch/pipermail/r-devel/2011-March/060262.html
## That has [A-Za-z], earlier versions [A-z], both of which may be
## invalid in some locales.
env0 <- "LC_COLLATE=C"
## texi2dvi, at least on OS X (4.8) does not accept TMPDIR with spaces.
if (grepl(" ", Sys.getenv("TMPDIR")))
env0 <- paste(env0, "TMPDIR=/tmp")
out <- .system_with_capture(texi2dvi,
c(opt_pdf, opt_quiet, opt_extra,
shQuote(file)),
env = env0)
log <- paste(file_path_sans_ext(file), "log", sep = ".")
## With Texinfo 6.1 (precisely, c6637), texi2dvi may not rerun
## often enough and give a non-zero status value when it should
## have continued iterating.
## Try to catch and correct cases seen on CRAN ...
## (Note that texi2dvi may have been run quietly, in which case
## diagnostics will only be in the log file.)
if(out$status &&
file_test("-f", log) &&
any(grepl("(Rerun to get|biblatex.*\\(re\\)run)",
readLines(log, warn = FALSE)))) {
out <- .system_with_capture(texi2dvi,
c(opt_pdf, opt_quiet, opt_extra,
shQuote(file)),
env = env0)
}
## We cannot necessarily rely on out$status, hence let us
## analyze the log files in any case.
errors <- character()
## (La)TeX errors.
log <- paste(file_path_sans_ext(file), "log", sep = ".")
if(file_test("-f", log)) {
lines <- .get_LaTeX_errors_from_log_file(log)
if(length(lines))
errors <- paste("LaTeX errors:",
paste(lines, collapse = "\n"),
sep = "\n")
}
## BibTeX errors.
log <- paste(file_path_sans_ext(file), "blg", sep = ".")
if(file_test("-f", log)) {
lines <- .get_BibTeX_errors_from_blg_file(log)
if(length(lines))
errors <- paste("BibTeX errors:",
paste(lines, collapse = "\n"),
sep = "\n")
}
msg <- ""
if(out$status) {
## <NOTE>
## If we cannot rely on out$status, we could test for
## if(out$status || length(errors))
## But shouldn't we be able to rely on out$status on Unix?
## </NOTE>
msg <- gettextf("Running 'texi2dvi' on '%s' failed.", file)
## Error messages from GNU texi2dvi are rather terse, so
## only use them in case no additional diagnostics are
## available (e.g, makeindex errors).
if(length(errors))
msg <- paste(msg, errors, sep = "\n")
else if(length(out$stderr))
msg <- paste(msg, "Messages:",
paste(out$stderr, collapse = "\n"),
sep = "\n")
if(!quiet)
msg <- paste(msg, "Output:",
paste(out$stdout, collapse = "\n"),
sep = "\n")
}
do_cleanup(clean)
if(nzchar(msg))
stop(msg, domain = NA)
else if(!quiet)
message(paste(paste(out$stderr, collapse = "\n"),
paste(out$stdout, collapse = "\n"),
sep = "\n"))
} else if(index && nzchar(texi2dvi)) { # MiKTeX on Windows
extra <- ""
## look for MiKTeX (which this almost certainly is)
## and set the path to R's style files.
## -I works in MiKTeX >= 2.4, at least
## http://docs.miktex.org/manual/texify.html
ver <- system(paste(shQuote(texi2dvi), "--version"), intern = TRUE)
if(length(grep("MiKTeX", ver[1L]))) {
## AFAICS need separate -I for each element of texinputs.
texinputs <- c(texinputs0, Rtexinputs, Rbstinputs)
texinputs <- gsub("\\", "/", texinputs, fixed = TRUE)
paths <- paste ("-I", shQuote(texinputs))
extra <- "--max-iterations=20"
extra <- paste(extra, paste(paths, collapse = " "))
}
## 'file' could be a file path
base <- basename(file_path_sans_ext(file))
## this only gives a failure in some cases, e.g. not for bibtex errors.
system(paste(shQuote(texi2dvi),
if(quiet) "--quiet" else "",
if(pdf) "--pdf" else "",
shQuote(file), extra),
intern=TRUE, ignore.stderr=TRUE)
msg <- ""
## (La)TeX errors.
logfile <- paste(base, "log", sep = ".")
if(file_test("-f", logfile)) {
lines <- .get_LaTeX_errors_from_log_file(logfile)
if(length(lines))
msg <- paste(msg, "LaTeX errors:",
paste(lines, collapse = "\n"),
sep = "\n")
}
## BibTeX errors.
logfile <- paste(base, "blg", sep = ".")
if(file_test("-f", logfile)) {
lines <- .get_BibTeX_errors_from_blg_file(logfile)
if(length(lines))
msg <- paste(msg, "BibTeX errors:",
paste(lines, collapse = "\n"),
sep = "\n")
}
do_cleanup(clean)
if(nzchar(msg)) {
msg <- paste(gettextf("running 'texi2dvi' on '%s' failed", file),
msg, "", sep = "\n")
stop(msg, call. = FALSE, domain = NA)
}
} else {
## Do not have texi2dvi or don't want to index
## Needed on Windows except for MiKTeX (prior to Sept 2015)
texfile <- shQuote(file)
## 'file' could be a file path
base <- basename(file_path_sans_ext(file))
idxfile <- paste0(base, ".idx")
latex <- if(pdf) Sys.getenv("PDFLATEX", "pdflatex")
else Sys.getenv("LATEX", "latex")
if(!nzchar(Sys.which(latex)))
stop(if(pdf) "pdflatex" else "latex", " is not available",
domain = NA)
sys2 <- if(quiet)
function(...) system2(..., stdout = FALSE, stderr = FALSE)
else system2
bibtex <- Sys.getenv("BIBTEX", "bibtex")
makeindex <- Sys.getenv("MAKEINDEX", "makeindex")
ltxargs <- c("-interaction=nonstopmode", texfile)
if(sys2(latex, ltxargs))
stop(gettextf("unable to run '%s' on '%s'", latex, file),
domain = NA)
nmiss <- length(grep("Warning:.*Citation.*undefined",
readLines(paste0(base, ".log"))))
for(iter in 1L:10L) { ## safety check
## This might fail as the citations have been included in the Rnw
if(nmiss) sys2(bibtex, shQuote(base))
nmiss_prev <- nmiss
if(index && file.exists(idxfile)) {
if(sys2(makeindex, shQuote(idxfile)))
stop(gettextf("unable to run '%s' on '%s'",
makeindex, idxfile),
domain = NA)
}
if(sys2(latex, ltxargs)) {
lines <- .get_LaTeX_errors_from_log_file(paste0(base, ".log"))
errors <- if(length(lines))
paste("LaTeX errors:",
paste(lines, collapse = "\n"), sep = "\n")
else character()
stop(paste(gettextf("unable to run %s on '%s'", latex, file),
errors, sep = "\n"),
domain = NA)
}
Log <- readLines(paste0(base, ".log"))
nmiss <- length(grep("Warning:.*Citation.*undefined", Log))
if(nmiss == nmiss_prev &&
!any(grepl("(Rerun to get|biblatex.*\\(re\\)run)", Log)) ) break
}
do_cleanup(clean)
}
invisible(NULL)
}
### * Internal utility variables.
### ** .BioC_version_associated_with_R_version
.BioC_version_associated_with_R_version <-
function() numeric_version(Sys.getenv("R_BIOC_VERSION", "3.3"))
## Things are more complicated from R-2.15.x with still two BioC
## releases a year, so we do need to set this manually.
## Wierdly, 3.0 is the second version (after 2.14) for the 3.1.x series.
### ** .vc_dir_names
## Version control directory names: CVS, .svn (Subversion), .arch-ids
## (arch), .bzr, .git, .hg (mercurial) and _darcs (Darcs)
## And it seems .metadata (eclipse) is in the same category.
.vc_dir_names <-
c("CVS", ".svn", ".arch-ids", ".bzr", ".git", ".hg", "_darcs", ".metadata")
## and RE version (beware of the need for escapes if amending)
.vc_dir_names_re <-
"/(CVS|\\.svn|\\.arch-ids|\\.bzr|\\.git|\\.hg|_darcs|\\.metadata)(/|$)"
## We are told
## .Rproj.user is Rstudio
## .cproject .project .settings are Eclipse
## .exrc is for vi
## .tm_properties is Mac's TextMate
.hidden_file_exclusions <-
c(".Renviron", ".Rprofile", ".Rproj.user",
".Rhistory", ".Rapp.history",
".tex", ".log", ".aux", ".pdf", ".png",
".backups", ".cvsignore", ".cproject", ".directory",
".dropbox", ".exrc", ".gdb.history",
".gitattributes", ".gitignore", ".gitmodules",
".hgignore", ".hgtags",
".htaccess",
".latex2html-init",
".project", ".seed", ".settings", ".tm_properties")
### * Internal utility functions.
### ** %w/o%
## x without y, as in the examples of ?match.
`%w/o%` <-
function(x, y)
x[!x %in% y]
### ** .OStype
.OStype <-
function()
{
OS <- Sys.getenv("R_OSTYPE")
if(nzchar(OS)) OS else .Platform$OS.type
}
### .R_top_srcdir
## Find the root directory of the source tree used for building this
## version of R (corresponding to Unix configure @top_srcdir@).
## Seems this is not recorded anywhere, but we can find our way ...
.R_top_srcdir_from_Rd <-
function() {
filebase <-
file_path_sans_ext(system.file("help", "tools.rdb",
package = "tools"))
path <- attr(fetchRdDB(filebase, "QC"), "Rdfile")
## We could use 5 dirname() calls, but perhaps more easily:
substring(path, 1L, nchar(path) - 28L)
}
## Unfortunately,
## .R_top_srcdir <- .R_top_srcdir_from_Rd()
## does not work because when tools is installed there are no Rd pages
## yet ...
### ** config_val_to_logical
config_val_to_logical <-
function(val) {
v <- tolower(val)
if (v %in% c("1", "yes", "true")) TRUE
else if (v %in% c("0", "no", "false")) FALSE
else {
warning(gettextf("cannot coerce %s to logical", sQuote(val)),
domain = NA)
NA
}
}
### ** .canonicalize_doi
.canonicalize_doi <-
function(x)
{
x <- sub("^((doi|DOI):)?[[:space:]]*http://(dx[.])?doi[.]org/", "",
x)
sub("^(doi|DOI):", "", x)
}
### ** .canonicalize_quotes
.canonicalize_quotes <-
function(txt)
{
txt <- gsub("(\xe2\x80\x98|\xe2\x80\x99)", "'", txt,
perl = TRUE, useBytes = TRUE)
txt <- gsub("(\xe2\x80\x9c|\xe2\x80\x9d)", '"', txt,
perl = TRUE, useBytes = TRUE)
txt
}
### ** .eval_with_capture
.eval_with_capture <-
function(expr, type = NULL)
{
## Evaluate the given expression and return a list with elements
## 'value', 'output' and 'message' (with obvious meanings).
## <NOTE>
## The current implementation gives character() if capturing was not
## attempted of gave nothing. If desired, one could modify the code
## to return NULL in the former case.
## </NOTE>
if(is.null(type))
capture_output <- capture_message <- TRUE
else {
type <- match.arg(type, c("output", "message"))
capture_output <- type == "output"
capture_message <- !capture_output
}
outcon <- file(open = "w+", encoding = "UTF-8")
msgcon <- file(open = "w+", encoding = "UTF-8")
if(capture_output) {
sink(outcon, type = "output")
on.exit(sink(type = "output"))
}
if(capture_message) {
sink(msgcon, type = "message")
on.exit(sink(type = "message"), add = capture_output)
}
on.exit({ close(outcon) ; close(msgcon) }, add = TRUE)
value <- eval(expr)
list(value = value,
output = readLines(outcon, encoding = "UTF-8", warn = FALSE),
message = readLines(msgcon, encoding = "UTF-8", warn = FALSE))
}
### ** .expand_anchored_Rd_xrefs
.expand_anchored_Rd_xrefs <-
function(db)
{
## db should have columns Target and Anchor.
db <- db[, c("Target", "Anchor"), drop = FALSE]
## See .check_Rd_xrefs().
anchor <- db[, 2L]
have_equals <- startsWith(anchor, "=")
if(any(have_equals))
db[have_equals, ] <-
cbind(sub("^=", "", anchor[have_equals]), "")
anchor <- db[, 2L]
have_colon <- grepl(":", anchor, fixed = TRUE)
y <- cbind(T_Package = anchor, T_File = db[, 1L])
y[have_colon, ] <-
cbind(sub("([^:]*):(.*)", "\\1", anchor[have_colon]),
sub("([^:]*):(.*)", "\\2", anchor[have_colon]))
y
}
### ** .file_append_ensuring_LFs
.file_append_ensuring_LFs <-
function(file1, file2)
{
## Use a fast version of file.append() that ensures LF between
## files.
.Call(codeFilesAppend, file1, file2)
}
### ** .file_path_relative_to_dir
.file_path_relative_to_dir <-
function(x, dir, add = FALSE)
{
if(any(ind <- (substring(x, 1L, nchar(dir)) == dir))) {
## Assume .Platform$file.sep is a single character.
x[ind] <- if(add)
file.path(basename(dir), substring(x[ind], nchar(dir) + 2L))
else
substring(x[ind], nchar(dir) + 2L)
}
x
}
### ** .find_calls
.find_calls <-
function(x, predicate = NULL, recursive = FALSE)
{
x <- if(is.call(x)) list(x) else as.list(x)
f <- if(is.null(predicate))
function(e) is.call(e)
else
function(e) is.call(e) && predicate(e)
if(!recursive) return(Filter(f, x))
calls <- list()
gatherer <- function(e) {
if(f(e)) calls <<- c(calls, list(e))
if(is.recursive(e))
for(i in seq_along(e)) gatherer(e[[i]])
}
gatherer(x)
calls
}
### ** .find_calls_in_file
.find_calls_in_file <-
function(file, encoding = NA, predicate = NULL, recursive = FALSE)
{
.find_calls(.parse_code_file(file, encoding), predicate, recursive)
}
### ** .find_calls_in_package_code
.find_calls_in_package_code <-
function(dir, predicate = NULL, recursive = FALSE, .worker = NULL)
{
dir <- file_path_as_absolute(dir)
dfile <- file.path(dir, "DESCRIPTION")
encoding <- if(file.exists(dfile))
.read_description(dfile)["Encoding"] else NA
if(is.null(.worker))
.worker <- function(file, encoding)
.find_calls_in_file(file, encoding, predicate, recursive)
code_files <-
list_files_with_type(file.path(dir, "R"), "code",
OS_subdirs = c("unix", "windows"))
calls <- lapply(code_files, .worker, encoding)
names(calls) <-
.file_path_relative_to_dir(code_files, dirname(dir))
calls
}
### ** .find_owner_env
.find_owner_env <-
function(v, env, last = NA, default = NA) {
while(!identical(env, last))
if(exists(v, envir = env, inherits = FALSE))
return(env)
else
env <- parent.env(env)
default
}
### ** .get_BibTeX_errors_from_blg_file
.get_BibTeX_errors_from_blg_file <-
function(con)
{
## Get BibTeX error info, using non-header lines until the first
## warning or summary, hoping for the best ...
lines <- readLines(con, warn = FALSE)
if(any(ind <- is.na(nchar(lines, allowNA = TRUE))))
lines[ind] <- iconv(lines[ind], "", "", sub = "byte")
## How can we find out for sure that there were errors? Try
## guessing ... and peeking at tex-buf.el from AUCTeX.
really_has_errors <-
(length(grep("^---", lines)) ||
regexpr("There (was|were) ([0123456789]+) error messages?",
lines[length(lines)]) > -1L)
## (Note that warnings are ignored for now.)
## MiKTeX does not give usage, so '(There were n error messages)' is
## last.
pos <- grep("^(Warning|You|\\(There)", lines)
if(!really_has_errors || !length(pos) ) return(character())
ind <- seq.int(from = 3L, length.out = pos[1L] - 3L)
lines[ind]
}
### ** .get_LaTeX_errors_from_log_file
.get_LaTeX_errors_from_log_file <-
function(con, n = 4L)
{
## Get (La)TeX lines with error plus n (default 4) lines of trailing
## context.
lines <- readLines(con, warn = FALSE)
if(any(ind <- is.na(nchar(lines, allowNA = TRUE))))
lines[ind] <- iconv(lines[ind], "", "", sub = "byte")
## Try matching both the regular error indicator ('!') as well as
## the file line error indicator ('file:line:').
pos <- grep("(^! |^!pdfTeX error:|:[0123456789]+:.*[Ee]rror)", lines)
## unforunately that was too general and caught false positives
## Errors are typically of the form
## ! LaTeX Error:
## !pdfTeX error:
## ! Emergency stop
## ! ==> Fatal error occurred, no output PDF file produced!
## .../pegas.Rcheck/inst/doc/ReadingFiles.tex:395: Package inputenc Error:
if(!length(pos)) return(character())
## Error chunk extends to at most the next error line.
mapply(function(from, to) paste(lines[from : to], collapse = "\n"),
pos, pmin(pos + n, c(pos[-1L], length(lines))))
}
### ** .get_internal_S3_generics
.get_internal_S3_generics <-
function(primitive = TRUE) # primitive means 'include primitives'
{
out <-
## Get the names of R internal S3 generics (via DispatchOrEval(),
## cf. zMethods.Rd).
c("[", "[[", "$", "[<-", "[[<-", "$<-",
"as.vector", "unlist",
.get_S3_primitive_generics()
## ^^^^^^^ now contains the members of the group generics from
## groupGeneric.Rd.
)
if(!primitive)
out <- out[!vapply(out, .is_primitive_in_base, NA)]
out
}
### ** .get_namespace_package_depends
.get_namespace_package_depends <-
function(dir, selective_only = FALSE)
{
nsInfo <- .check_namespace(dir)
getter <- if(selective_only) {
function(e) {
if(is.list(e) && length(e[[2L]])) e[[1L]] else character()
}
} else {
function(e) e[[1L]]
}
depends <- c(lapply(nsInfo$imports, getter),
lapply(nsInfo$importClasses, getter),
lapply(nsInfo$importMethods, getter))
unique(sort(as.character(unlist(depends, use.names = FALSE))))
}
### ** .get_namespace_S3_methods_db
.get_namespace_S3_methods_db <-
function(nsInfo)
{
## Get the registered S3 methods for an 'nsInfo' object returned by
## parseNamespaceFile(), as a 3-column character matrix with the
## names of the generic, class and method (as a function).
S3_methods_list <- nsInfo$S3methods
if(!length(S3_methods_list)) return(matrix(character(), ncol = 3L))
idx <- is.na(S3_methods_list[, 3L])
S3_methods_list[idx, 3L] <-
paste(S3_methods_list[idx, 1L],
S3_methods_list[idx, 2L],
sep = ".")
S3_methods_list
}
### ** .get_package_metadata
.get_package_metadata <-
function(dir, installed = FALSE)
{
## Get the package DESCRIPTION metadata for a package with root
## directory 'dir'. If an unpacked source (uninstalled) package,
## base packages (have only a DESCRIPTION.in file with priority
## "base") need special attention.
dir <- file_path_as_absolute(dir)
dfile <- file.path(dir, "DESCRIPTION")
if(file_test("-f", dfile)) return(.read_description(dfile))
if(installed) stop("File 'DESCRIPTION' is missing.")
dfile <- file.path(dir, "DESCRIPTION.in")
if(file_test("-f", dfile))
meta <- .read_description(dfile)
else
stop("Files 'DESCRIPTION' and 'DESCRIPTION.in' are missing.")
if(identical(as.character(meta["Priority"]), "base")) return(meta)
stop("invalid package layout")
}
### ** .get_repositories
.get_repositories <-
function()
{
rfile <- Sys.getenv("R_REPOSITORIES", unset = NA_character_)
if(is.na(rfile) || !file_test("-f", rfile)) {
rfile <- file.path(Sys.getenv("HOME"), ".R", "repositories")
if(!file_test("-f", rfile))
rfile <- file.path(R.home("etc"), "repositories")
}
.read_repositories(rfile)
}
### ** .get_requires_from_package_db
.get_requires_from_package_db <-
function(db,
category = c("Depends", "Imports", "LinkingTo", "VignetteBuilder",
"Suggests", "Enhances"))
{
category <- match.arg(category)
if(category %in% names(db)) {
requires <- unlist(strsplit(db[category], ","))
requires <-
sub("^[[:space:]]*([[:alnum:].]+).*$", "\\1", requires)
if(category == "Depends")
requires <- requires[requires != "R"]
}
else
requires <- character()
requires
}
### ** .get_requires_with_version_from_package_db
.get_requires_with_version_from_package_db <-
function(db,
category = c("Depends", "Imports", "LinkingTo", "VignetteBuilder",
"Suggests", "Enhances"))
{
category <- match.arg(category)
if(category %in% names(db)) {
res <- .split_dependencies(db[category])
if(category == "Depends") res[names(res) != "R"] else res
} else list()
}
### ** .get_S3_generics_as_seen_from_package
.get_S3_generics_as_seen_from_package <-
function(dir, installed = TRUE, primitive = FALSE)
{
## Get the S3 generics "as seen from a package" rooted at
## @code{dir}. Tricky ...
if(basename(dir) == "base")
env_list <- list()
else {
## Always look for generics in the whole of the former base.
## (Not right, but we do not perform run time analyses when
## working off package sources.) Maybe change this eventually,
## but we still cannot rely on packages to fully declare their
## dependencies on base packages.
env_list <-
list(baseenv(),
as.environment("package:graphics"),
as.environment("package:stats"),
as.environment("package:utils"))
if(installed) {
## Also use the loaded namespaces and attached packages
## listed in the DESCRIPTION Depends and Imports fields.
## Not sure if this is the best approach: we could also try
## to determine which namespaces/packages were made
## available by loading the package (which should work at
## least when run from R CMD check), or we could simply
## attach every package listed as a dependency ... or
## perhaps do both.
db <- .read_description(file.path(dir, "DESCRIPTION"))
depends <- .get_requires_from_package_db(db, "Depends")
imports <- .get_requires_from_package_db(db, "Imports")
reqs <- intersect(c(depends, imports), loadedNamespaces())
if(length(reqs))
env_list <- c(env_list, lapply(reqs, getNamespace))
reqs <- intersect(setdiff(depends, loadedNamespaces()),
.packages())
if(length(reqs))
env_list <- c(env_list, lapply(reqs, .package_env))
env_list <- unique(env_list)
}
}
## some BioC packages warn here
suppressWarnings(
unique(c(.get_internal_S3_generics(primitive),
unlist(lapply(env_list,
function(env) {
nms <- sort(names(env))
if(".no_S3_generics" %in% nms)
character()
else Filter(function(f)
.is_S3_generic(f, envir = env),
nms)
})))))
}