Skip to content

Commit 3e6d569

Browse files
authored
Merge pull request #496 from sderev/feature/cli-version-option
Add `--version` option to CLI
2 parents aa50f37 + 87880e7 commit 3e6d569

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

youtube_transcript_api/_cli.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import argparse
2+
from importlib.metadata import PackageNotFoundError, version
23
from typing import List
34

45
from .proxies import GenericProxyConfig, WebshareProxyConfig
@@ -91,6 +92,12 @@ def _fetch_transcript(
9192

9293
return transcript.fetch()
9394

95+
def _get_version(self):
96+
try:
97+
return version("youtube-transcript-api")
98+
except PackageNotFoundError:
99+
return "unknown"
100+
94101
def _parse_args(self):
95102
parser = argparse.ArgumentParser(
96103
description=(
@@ -99,6 +106,11 @@ def _parse_args(self):
99106
"other selenium based solutions do!"
100107
)
101108
)
109+
parser.add_argument(
110+
"--version",
111+
action="version",
112+
version=f"%(prog)s, version {self._get_version()}",
113+
)
102114
parser.add_argument(
103115
"--list-transcripts",
104116
action="store_const",

youtube_transcript_api/test/test_cli.py

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import pytest
2+
from importlib.metadata import PackageNotFoundError, version
23
from unittest import TestCase
3-
from unittest.mock import MagicMock
4+
from unittest.mock import MagicMock, patch
45

56
import json
7+
import subprocess
68

79
from youtube_transcript_api import (
810
YouTubeTranscriptApi,
@@ -340,3 +342,29 @@ def test_run__cookies(self):
340342
proxy_config=None,
341343
cookie_path="blahblah.txt",
342344
)
345+
346+
def test_version_matches_metadata(self):
347+
"""
348+
`youtube_transcript_api --version` should return the same version as in the package metadata.
349+
"""
350+
expected_version_msg = (
351+
f"youtube_transcript_api, version {version('youtube-transcript-api')}"
352+
)
353+
354+
cli_version_msg = subprocess.run(
355+
["youtube_transcript_api", "--version"],
356+
capture_output=True,
357+
text=True,
358+
check=True,
359+
).stdout.strip()
360+
361+
assert (
362+
cli_version_msg == expected_version_msg
363+
), f"Expected version '{expected_version_msg}', but got '{cli_version_msg}'"
364+
365+
def test_get_version_package_not_found(self):
366+
with patch(
367+
"youtube_transcript_api._cli.version", side_effect=PackageNotFoundError
368+
):
369+
cli = YouTubeTranscriptCli([])
370+
assert cli._get_version() == "unknown"

0 commit comments

Comments
 (0)