Skip to content

.destfile unexpectedly written even on error #178

Description

@arcresu

When .destfile is provided, gh will write to it even if the API returned an error:

library(gh)

# trying to download a file from a github repo that unexpectedly doesn't exist
> gh("/repos/r-lib/gh/contents/DOES_NOT_EXIST", .destfile="gh_destfile", .accept = "application/vnd.github.v3.raw")
Error in `gh_process_response()`:
! GitHub API error (404): Not FoundURL not found:
  <https://api.github.com/repos/r-lib/gh/contents/DOES_NOT_EXIST>Read more at
  <https://docs.github.com/rest/reference/repos#get-repository-content>

> readLines(file("gh_destfile"), warn=FALSE)
[1] "{\"message\":\"Not Found\",\"documentation_url\":\"https://docs.github.com/rest/reference/repos#get-repository-content\"}

In the absence of .destfile, when the request succeeds (e.g. change DOES_NOT_EXIST to README.md), the contents of the file are printed out. When it fails there's an error message, but nothing else is printed. However when .destfile is given, that file is written to whether or not the request succeeded. In the error case, the JSON-encoded error is put in the file even when .accept specified that we were expecting to write something other than JSON.

It's a bit of a surprising behaviour, and it's the underlying cause of a bug in usethis (r-lib/usethis#1774). Granted, usethis could have been handling the error more carefully.

I think it would be less surprising if the .destfile were only created and written when the API request succeeded. All data from the API error already appears in the R error, so we don't lose any information.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behavior

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions