Skip to content

openscience import reports a malformed session file as not found and exits 0 #814

Closed

Description

What happens

src/cli/cmd/import.ts read the export file like this:

const file = Bun.file(args.file)
exportData = await file.json().catch(() => {})
if (!exportData) {
  process.stdout.write(`File not found: ${args.file}`)
  process.stdout.write(EOL)
  return
}

if (!exportData) {                                    // unreachable
  process.stdout.write(`Failed to read session data`)
  process.stdout.write(EOL)
  return
}

Three problems in eleven lines.

  1. .catch(() => {}) swallows every failure identically, so a file that exists but is not valid JSON is reported as "File not found".
  2. The second if (!exportData) block is dead code — the first one already returned. The Failed to read session data message can never be printed.
  3. Neither path sets a non-zero exit code, so openscience import bad.json exits 0 whether the file was missing, corrupt, or imported.

Why it is wrong

File not found: /path/you/just/typed sends the user looking for a path that is sitting right there. The real cause — a truncated export, a merge conflict marker, a truncated download, a JSONC file — is invisible.

The exit code matters more. import is the natural way to move a session between machines and to script a restore, and a script that runs openscience import backup.json && echo done prints done after a completely failed import.

There is a third, quieter failure: valid JSON that is not a session export. {"hello": "world"} parses fine, so !exportData is false, and the next line is exportData.info.id — a TypeError on undefined.

Reproduction

Verified against the original code on this machine:

$ echo '{ this is not json' > bad.json
$ openscience import bad.json
File not found: C:\...\bad.json        <- the file exists
$ echo $?
0                                      <- success

And with a non-export JSON object, the command throws TypeError: Cannot read properties of undefined (reading 'id').

Suggested fix

Extract the read into a small helper that separates the failure modes:

  • check Bun.file(file).exists() first, so a missing file says so
  • try/catch the parse and include the parser's own message
  • check the parsed shape has info and messages before using it
  • write failures to stderr and set process.exitCode = 1

This also deletes the unreachable duplicate branch. test/cli/import-input.test.ts covers all five cases: well-formed, malformed, missing, valid-JSON-wrong-shape, and empty file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions