Bug 16712

Summary: available.packages deletes local repository PACKAGES file upon unsuccessful CRAN connection
Product: R Reporter: forest.fang <forest.fang>
Component: InstallationAssignee: R-core <R-core>
Status: CLOSED FIXED    
Severity: major CC: murdoch
Priority: P5    
Version: R 3.2.3   
Hardware: All   
OS: All   

Description forest.fang@outlook.com 2016-02-12 15:01:01 UTC
See title. The steps to reproduce this issue is as follows:

if (!requireNamespace("miniCRAN", quietly = TRUE)) {
# create a local repository
## Create temporary folder for miniCRAN
dir.create(pth <- file.path(tempdir(), "miniCRAN"))
## Make repo for source that contains bitops R package
miniCRAN::makeRepo("bitops", path=pth, type="source")

# List all files in miniCRAN
list.files(pth, recursive=TRUE, full.names=FALSE)

# set repos to a bad CRAN mirro and miniCRAN
options(repos = c(CRAN="http://fake.cran.com", miniCRAN=file.path("file://", pth)))

# run available.packages (expecting CRAN fetch to fail)
df <- available.packages()

# List all files in miniCRAN again
list.files(pth, recursive=TRUE, full.names=FALSE)
# NOTE PACKAGES file has been deleted

The intermediate results that display the symptom is as follows:

Before running available.packages
> list.files(pth, recursive=TRUE, full.names=FALSE)
[1] "src/contrib/bitops_1.0-6.tar.gz" "src/contrib/PACKAGES"           
[3] "src/contrib/PACKAGES.gz"  
After running available.packages (and CRAN connection fails)
> list.files(pth, recursive=TRUE, full.names=FALSE)
[1] "src/contrib/bitops_1.0-6.tar.gz" "src/contrib/PACKAGES.gz" 

This can be a major headache as CRAN connection could fail due to a bad internet connection or incorrect HTTP proxy settings. 

The issue stems from this code block within available.packages function:
                if (inherits(z, "error")) {
                  warning(gettextf("unable to access index for repository %s", 
                    repos), ":\n  ", conditionMessage(z), call. = FALSE, 
                    immediate. = TRUE, domain = NA)
The next is called here upon error but before an on.exit is registered:
tmpf <- tempfile()
Unfortunately tmpf variable is later set to the PACKAGES file in the local repository.
We can add these before next to address this issue:

p.s. First bug report on r-project. Apologize for any incorrect etiquette in advance.
Comment 1 Duncan Murdoch 2016-02-14 18:55:55 UTC
Thanks for the report.  I'll fix it (with a slightly different fix than your suggestion:  I'll just move the unlink earlier.  tmpf isn't needed again by the time we get to the "next", as far as I can see.

Will commit soon after testing; I expect this will make it into R-patched as well as R-devel