# Buggy code
def save_readability(
    link: Link, out_dir: Optional[str] = None, timeout: int = TIMEOUT
) -> ArchiveResult:
    """download reader friendly version using @mozilla/readability"""

    out_dir = Path(out_dir or link.link_dir)
    output_folder = out_dir.absolute() / "readability"
    output = str(output_folder)

    # Readability Docs: https://github.com/mozilla/readability

    status = "succeeded"
    timer = TimedProgress(timeout, prefix="      ")
    try:
        document = get_html(link, out_dir)
        temp_doc = NamedTemporaryFile(delete=False)
        temp_doc.write(document.encode("utf-8"))
        temp_doc.close()

        cmd = [DEPENDENCIES["READABILITY_BINARY"]["path"], temp_doc.name]

        result = run(cmd, cwd=out_dir, timeout=timeout)
        result_json = json.loads(result.stdout)
        output_folder.mkdir(exist_ok=True)
        atomic_write(str(output_folder / "content.html"), result_json.pop("content"))
        atomic_write(str(output_folder / "content.txt"), result_json.pop("textContent"))
        atomic_write(str(output_folder / "article.json"), result_json)

        # parse out number of files downloaded from last line of stderr:
        #  "Downloaded: 76 files, 4.0M in 1.6s (2.52 MB/s)"
        output_tail = [
            line.strip()
            for line in (result.stdout + result.stderr).decode().rsplit("\n", 3)[-3:]
            if line.strip()
        ]
        hints = (
            "Got readability response code: {}.".format(result.returncode),
            *output_tail,
        )

        # Check for common failure cases
        if result.returncode > 0:
            raise ArchiveError("Readability was not able to archive the page", hints)
    except (Exception, OSError) as err:
        status = "failed"
        output = err
    finally:
        timer.end()

    return ArchiveResult(
        cmd=cmd,
        pwd=str(out_dir),
        cmd_version=READABILITY_VERSION,
        output=output,
        status=status,
        **timer.stats,
    )


# Traceback (UnboundLocalError)
[√] [2020-08-26 21:10:43] "Big Brother is Watching - '17 WRX Limited and all '17 STI - Page 3 - NASIOC"
https://forums.nasioc.com/forums/showthread.php?t=2803387&amp;amp;highlight=big+brother&amp;amp;page=3
√ ./archive/1576899114
> readability
! Failed to archive link: Exception: Exception in archive_methods.save_readability(Link(url=https://forums.nasioc.com/forums/showthread.php?t=2803387&amp;amp;highlight=big+brother&amp;amp;page=3))

Traceback (most recent call last):
File "/app/archivebox/extractors/__init__.py", line 91, in archive_link
result = method_function(link=link, out_dir=out_dir)
File "/app/archivebox/util.py", line 111, in typechecked_function
return func(*args, **kwargs)
File "/app/archivebox/extractors/readability.py", line 109, in save_readability
cmd=cmd,
UnboundLocalError: local variable 'cmd' referenced before assignment

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/usr/local/bin/archivebox", line 33, in <module>
sys.exit(load_entry_point('archivebox', 'console_scripts', 'archivebox')())
File "/app/archivebox/cli/__init__.py", line 122, in main
run_subcommand(
File "/app/archivebox/cli/__init__.py", line 62, in run_subcommand
module.main(args=subcommand_args, stdin=stdin, pwd=pwd)    # type: ignore
File "/app/archivebox/cli/archivebox_add.py", line 78, in main
add(
File "/app/archivebox/util.py", line 111, in typechecked_function
return func(*args, **kwargs)
File "/app/archivebox/main.py", line 572, in add
archive_links(all_links, overwrite=overwrite, out_dir=out_dir)
File "/app/archivebox/util.py", line 111, in typechecked_function
return func(*args, **kwargs)
File "/app/archivebox/extractors/__init__.py", line 150, in archive_links
archive_link(link, overwrite=overwrite, methods=methods, out_dir=link.link_dir)
File "/app/archivebox/util.py", line 111, in typechecked_function
return func(*args, **kwargs)
File "/app/archivebox/extractors/__init__.py", line 101, in archive_link
raise Exception('Exception in archive_methods.save_{}(Link(url={}))'.format(
Exception: Exception in archive_methods.save_readability(Link(url=https://forums.nasioc.com/forums/showthread.php?t=2803387&amp;amp;highlight=big+brother&amp;amp;page=3))

# Fixed code
def save_readability(
    link: Link, out_dir: Optional[str] = None, timeout: int = TIMEOUT
) -> ArchiveResult:
    """download reader friendly version using @mozilla/readability"""

    out_dir = Path(out_dir or link.link_dir)
    output_folder = out_dir.absolute() / "readability"
    output = str(output_folder)

    # Readability Docs: https://github.com/mozilla/readability

    status = "succeeded"
    # fake command to show the user so they have something to try debugging if get_html fails
    cmd = [CURL_BINARY, link.url]
    timer = TimedProgress(timeout, prefix="      ")
    try:
        document = get_html(link, out_dir)
        temp_doc = NamedTemporaryFile(delete=False)
        temp_doc.write(document.encode("utf-8"))
        temp_doc.close()

        cmd = [DEPENDENCIES["READABILITY_BINARY"]["path"], temp_doc.name]

        result = run(cmd, cwd=out_dir, timeout=timeout)
        result_json = json.loads(result.stdout)
        output_folder.mkdir(exist_ok=True)
        atomic_write(str(output_folder / "content.html"), result_json.pop("content"))
        atomic_write(str(output_folder / "content.txt"), result_json.pop("textContent"))
        atomic_write(str(output_folder / "article.json"), result_json)

        # parse out number of files downloaded from last line of stderr:
        #  "Downloaded: 76 files, 4.0M in 1.6s (2.52 MB/s)"
        output_tail = [
            line.strip()
            for line in (result.stdout + result.stderr).decode().rsplit("\n", 3)[-3:]
            if line.strip()
        ]
        hints = (
            "Got readability response code: {}.".format(result.returncode),
            *output_tail,
        )

        # Check for common failure cases
        if result.returncode > 0:
            raise ArchiveError("Readability was not able to archive the page", hints)
    except (Exception, OSError) as err:
        status = "failed"
        output = err
    finally:
        timer.end()

    return ArchiveResult(
        cmd=cmd,
        pwd=str(out_dir),
        cmd_version=READABILITY_VERSION,
        output=output,
        status=status,
        **timer.stats,
    )