Skip to content

Commit 2754185

Browse files
committed
ruff
1 parent 5d94aaf commit 2754185

22 files changed

+1989
-2005
lines changed

examples/cache_management.py

Lines changed: 109 additions & 107 deletions
Large diffs are not rendered by default.

examples/cache_timestamps.py

Lines changed: 54 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -19,69 +19,69 @@ def demonstrate_cache_timestamps():
1919
"""Demonstrate accessing cache timestamp information."""
2020
print("Cache Timestamp Information Demo")
2121
print("=" * 40)
22-
22+
2323
# Create a repository with a cache backend
2424
cache = EphemeralCache(max_keys=100)
25-
repo = Repository(working_dir=GIT_PANDAS_DIR, cache_backend=cache, default_branch='master')
26-
25+
repo = Repository(working_dir=GIT_PANDAS_DIR, cache_backend=cache, default_branch="master")
26+
2727
print(f"Repository: {repo.repo_name}")
2828
print(f"Cache backend: {type(cache).__name__}")
2929
print()
30-
30+
3131
# Call some methods to populate the cache
3232
print("Populating cache with repository data...")
33-
33+
3434
print(" - Getting commit history...")
35-
commit_history = repo.commit_history(limit=10)
36-
35+
repo.commit_history(limit=10)
36+
3737
print(" - Getting file list...")
38-
files = repo.list_files()
39-
38+
repo.list_files()
39+
4040
print(" - Getting blame information...")
41-
blame = repo.blame()
42-
41+
repo.blame()
42+
4343
print(f"Cache now contains {len(cache._cache)} entries")
4444
print()
45-
45+
4646
# Show cache information
4747
print("Cache Contents and Timestamps:")
4848
print("-" * 40)
49-
49+
5050
cached_keys = cache.list_cached_keys()
5151
for entry in cached_keys:
5252
print(f"Key: {entry['key']}")
5353
print(f" Cached at: {entry['cached_at'].strftime('%Y-%m-%d %H:%M:%S UTC')}")
5454
print(f" Age: {entry['age_seconds']:.1f} seconds")
5555
print()
56-
56+
5757
# Wait a moment and call one method again
5858
print("Waiting 2 seconds and refreshing commit history...")
5959
time.sleep(2)
60-
60+
6161
# This should hit the cache
62-
commit_history_cached = repo.commit_history(limit=10)
63-
62+
repo.commit_history(limit=10)
63+
6464
# This should create a new cache entry
65-
commit_history_fresh = repo.commit_history(limit=20)
66-
65+
repo.commit_history(limit=20)
66+
6767
print("\nUpdated cache contents:")
6868
print("-" * 40)
69-
69+
7070
cached_keys = cache.list_cached_keys()
7171
for entry in cached_keys:
7272
print(f"Key: {entry['key']}")
7373
print(f" Cached at: {entry['cached_at'].strftime('%Y-%m-%d %H:%M:%S UTC')}")
7474
print(f" Age: {entry['age_seconds']:.1f} seconds")
7575
print()
76-
76+
7777
# Demonstrate getting specific cache info
7878
print("Getting specific cache information:")
7979
print("-" * 40)
80-
80+
8181
# Find a commit_history cache key
82-
commit_keys = [k for k in cached_keys if 'commit_history' in k['key']]
82+
commit_keys = [k for k in cached_keys if "commit_history" in k["key"]]
8383
if commit_keys:
84-
key = commit_keys[0]['key']
84+
key = commit_keys[0]["key"]
8585
info = cache.get_cache_info(key)
8686
if info:
8787
print(f"Cache info for key '{key}':")
@@ -95,44 +95,43 @@ def demonstrate_disk_cache_persistence():
9595
print("\n" + "=" * 50)
9696
print("Disk Cache Persistence Demo")
9797
print("=" * 50)
98-
98+
9999
cache_file = "/tmp/gitpandas_demo_cache.gz"
100-
100+
101101
# Clean up any existing cache file
102102
if os.path.exists(cache_file):
103103
os.remove(cache_file)
104-
104+
105105
print("Creating repository with DiskCache...")
106106
cache = DiskCache(filepath=cache_file, max_keys=50)
107-
repo = Repository(working_dir=GIT_PANDAS_DIR, cache_backend=cache, default_branch='master')
108-
107+
repo = Repository(working_dir=GIT_PANDAS_DIR, cache_backend=cache, default_branch="master")
108+
109109
# Populate cache
110110
print("Populating cache...")
111-
commit_history = repo.commit_history(limit=5)
112-
files = repo.list_files()
113-
111+
repo.commit_history(limit=5)
112+
repo.list_files()
113+
114114
print(f"Cache file created: {cache_file}")
115115
print(f"Cache contains {len(cache._cache)} entries")
116-
116+
117117
# Show initial cache info
118118
cached_keys = cache.list_cached_keys()
119119
print("\nInitial cache entries:")
120120
for entry in cached_keys:
121121
print(f" {entry['key']}: {entry['cached_at'].strftime('%H:%M:%S')}")
122-
122+
123123
# Create a new cache instance from the same file
124124
print("\nCreating new cache instance from saved file...")
125125
cache2 = DiskCache(filepath=cache_file, max_keys=50)
126-
126+
127127
print(f"Loaded cache contains {len(cache2._cache)} entries")
128-
128+
129129
# Show loaded cache info
130130
cached_keys2 = cache2.list_cached_keys()
131131
print("\nLoaded cache entries:")
132132
for entry in cached_keys2:
133-
print(f" {entry['key']}: {entry['cached_at'].strftime('%H:%M:%S')} "
134-
f"(age: {entry['age_seconds']:.1f}s)")
135-
133+
print(f" {entry['key']}: {entry['cached_at'].strftime('%H:%M:%S')} (age: {entry['age_seconds']:.1f}s)")
134+
136135
# Clean up
137136
if os.path.exists(cache_file):
138137
os.remove(cache_file)
@@ -144,29 +143,29 @@ def demonstrate_cache_with_force_refresh():
144143
print("\n" + "=" * 50)
145144
print("Force Refresh Demo")
146145
print("=" * 50)
147-
146+
148147
cache = EphemeralCache(max_keys=10)
149-
repo = Repository(working_dir=GIT_PANDAS_DIR, cache_backend=cache, default_branch='master')
150-
148+
repo = Repository(working_dir=GIT_PANDAS_DIR, cache_backend=cache, default_branch="master")
149+
151150
print("Getting commit history (first time)...")
152151
start_time = datetime.now(timezone.utc)
153-
commit_history1 = repo.commit_history(limit=5)
154-
152+
repo.commit_history(limit=5)
153+
155154
time.sleep(1)
156-
155+
157156
print("Getting commit history (should use cache)...")
158-
commit_history2 = repo.commit_history(limit=5)
159-
157+
repo.commit_history(limit=5)
158+
160159
time.sleep(1)
161-
160+
162161
print("Getting commit history with force_refresh=True...")
163-
commit_history3 = repo.commit_history(limit=5, force_refresh=True)
164-
162+
repo.commit_history(limit=5, force_refresh=True)
163+
165164
print("\nCache timeline:")
166165
cached_keys = cache.list_cached_keys()
167166
for entry in cached_keys:
168-
if 'commit_history' in entry['key']:
169-
age_from_start = (entry['cached_at'] - start_time).total_seconds()
167+
if "commit_history" in entry["key"]:
168+
age_from_start = (entry["cached_at"] - start_time).total_seconds()
170169
print(f" Commit history cached at: +{age_from_start:.1f}s from start")
171170
print(f" Current age: {entry['age_seconds']:.1f}s")
172171

@@ -176,15 +175,15 @@ def demonstrate_cache_with_force_refresh():
176175
demonstrate_cache_timestamps()
177176
demonstrate_disk_cache_persistence()
178177
demonstrate_cache_with_force_refresh()
179-
178+
180179
print("\n" + "=" * 50)
181180
print("Summary:")
182181
print("- Cache backends now track when entries were created")
183182
print("- No changes to Repository or ProjectDirectory API")
184183
print("- Users can access cache info via cache_backend.get_cache_info()")
185184
print("- Users can list all cached keys via cache_backend.list_cached_keys()")
186185
print("- Backward compatibility maintained with existing caches")
187-
186+
188187
except Exception as e:
189188
print(f"Error running demo: {e}")
190-
print("Make sure you're running this from the git-pandas directory")
189+
print("Make sure you're running this from the git-pandas directory")

examples/release_analytics.py

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
"""
66

77
import pandas as pd
8+
89
from gitpandas import Repository
910

1011
# --- Instantiate Repository ---
@@ -22,7 +23,7 @@
2223
print(f"Cloned to temporary directory: {repo.git_dir}")
2324
except Exception as e:
2425
print(f"Error instantiating repository: {e}")
25-
repo = None # Ensure repo is None if instantiation fails
26+
repo = None # Ensure repo is None if instantiation fails
2627

2728
# --- Call release_tag_summary ---
2829
if repo:
@@ -46,20 +47,20 @@
4647
print(release_summary_df)
4748

4849
# Example of how to access specific information:
49-
if 'tag' in release_summary_df.columns and len(release_summary_df) > 1:
50+
if "tag" in release_summary_df.columns and len(release_summary_df) > 1:
5051
# Show files changed between the first two listed tags (if available)
5152
# Note: The first tag in the summary won't have "previous tag" data.
52-
second_tag_entry = release_summary_df.iloc[1] # Second tag in the sorted list
53+
second_tag_entry = release_summary_df.iloc[1] # Second tag in the sorted list
5354
print(f"\nExample: Files changed for tag '{second_tag_entry['tag']}' (since previous tag):")
54-
if isinstance(second_tag_entry['files'], list) and second_tag_entry['files']:
55-
for file_path in second_tag_entry['files']:
55+
if isinstance(second_tag_entry["files"], list) and second_tag_entry["files"]:
56+
for file_path in second_tag_entry["files"]:
5657
print(f" - {file_path}")
5758
else:
5859
print(" No files listed or files column is not a list.")
5960

60-
elif release_summary_df is not None: # Empty DataFrame
61+
elif release_summary_df is not None: # Empty DataFrame
6162
print("No release summary data returned. The repository might not have tags, or no tags match the glob.")
62-
else: # None was returned, indicating an issue
63+
else: # None was returned, indicating an issue
6364
print("Failed to retrieve release summary (method returned None).")
6465

6566
except Exception as e:
@@ -77,34 +78,38 @@
7778
# As this is a brief example, we'll try to pick one from the summary if possible,
7879
# otherwise, we'll use a placeholder.
7980
target_commit_sha = None
80-
if 'release_summary_df' in locals() and not release_summary_df.empty and 'commit_sha' in release_summary_df.columns:
81+
if "release_summary_df" in locals() and not release_summary_df.empty and "commit_sha" in release_summary_df.columns:
8182
# Let's try to get the commit SHA of the first tag listed (if any)
8283
# This commit is what the tag points to.
83-
potential_sha = release_summary_df['commit_sha'].iloc[0]
84-
if pd.notna(potential_sha): # Check if the SHA is not NaN or None
84+
potential_sha = release_summary_df["commit_sha"].iloc[0]
85+
if pd.notna(potential_sha): # Check if the SHA is not NaN or None
8586
target_commit_sha = potential_sha
8687
print(f"Attempting to get content for commit SHA (from first tag's commit_sha): {target_commit_sha}")
8788
else:
8889
print("Could not get a valid commit SHA from the release_summary_df's first entry.")
89-
90+
9091
if not target_commit_sha:
91-
target_commit_sha = "PLACEHOLDER_COMMIT_SHA" # Replace with an actual commit SHA from the repo
92+
target_commit_sha = "PLACEHOLDER_COMMIT_SHA" # Replace with an actual commit SHA from the repo
9293
print(f"Using placeholder commit SHA: {target_commit_sha}. Replace with a real one for actual output.")
9394

9495
if target_commit_sha != "PLACEHOLDER_COMMIT_SHA":
9596
try:
9697
# The 'rev' parameter takes the commit SHA.
9798
commit_content_df = repo.get_commit_content(rev=target_commit_sha)
98-
99+
99100
if commit_content_df is not None and not commit_content_df.empty:
100101
print(f"Content changes for commit {target_commit_sha} (showing first 5 lines):")
101102
# Displaying only a part of the DataFrame for brevity.
102103
# Columns typically include: 'file_path', 'change_type', 'diff', 'old_blob_sha', 'new_blob_sha'
103104
print(commit_content_df.head())
104-
elif commit_content_df is not None: # Empty DataFrame
105-
print(f"No content changes (e.g. diffs) found for commit {target_commit_sha}. This can be normal for merge commits with no textual changes, or if the commit only modified tree structure.")
106-
else: # None was returned
107-
print(f"Failed to get content for commit {target_commit_sha} (method returned None). Could be an invalid SHA or repository issue.")
105+
elif commit_content_df is not None: # Empty DataFrame
106+
print(
107+
f"No content changes (e.g. diffs) found for commit {target_commit_sha}. This can be normal for merge commits with no textual changes, or if the commit only modified tree structure."
108+
)
109+
else: # None was returned
110+
print(
111+
f"Failed to get content for commit {target_commit_sha} (method returned None). Could be an invalid SHA or repository issue."
112+
)
108113
except Exception as e:
109114
print(f"Error calling get_commit_content for {target_commit_sha}: {e}")
110115
else:

0 commit comments

Comments
 (0)