-
-
Notifications
You must be signed in to change notification settings - Fork 369
Expand file tree
/
Copy pathversion_storage_report.py
More file actions
136 lines (106 loc) · 4.44 KB
/
Copy pathversion_storage_report.py
File metadata and controls
136 lines (106 loc) · 4.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
"""
Analyze file version storage across a SharePoint document library.
Reports the number of versions per file, their storage cost, and
identifies candidates for version cleanup (files with excessive
versions that consume disproportionate storage).
Inspired by Report-SPOFileVersions.PS1 from Office 365 for IT Pros.
Required delegated permissions:
Sites.Read.All Read files, libraries, and version history
https://learn.microsoft.com/en-us/sharepoint/dev/apis/rest-api
"""
import argparse
from typing import List
from office365.sharepoint.client_context import ClientContext
from tests.settings import client_id, password, site_url, tenant, username
_KB = 1024
_VERSION_THRESHOLD = 20
def format_bytes(size: int) -> str:
"""Format byte count to human-readable string."""
if size >= _KB**3:
return f"{size / (_KB**3):.2f} GB"
elif size >= _KB**2:
return f"{size / (_KB**2):.2f} MB"
elif size >= _KB:
return f"{size / _KB:.2f} KB"
return f"{size} B"
def analyze_version_storage(ctx: ClientContext, library_name: str = "Shared Documents") -> List[dict]:
"""Analyze file version storage in a document library.
Args:
ctx: Authenticated ClientContext.
library_name: Name of the document library to scan.
Returns:
List of file dicts with version count, total version size, and current size.
"""
results = []
try:
lib = ctx.web.lists.get_by_title(library_name)
files = lib.root_folder.files.expand(["Versions"]).get().execute_query()
except Exception as e:
print(f" Error accessing library '{library_name}': {e}")
return results
for f in files:
version_count = 0
total_version_size = 0
current_size = getattr(f, "length", 0)
try:
versions = f.versions
if versions:
version_count = len(versions)
for v in versions:
total_version_size += getattr(v, "size", 0) or 0
except Exception:
pass
results.append(
{
"name": getattr(f, "name", "Unknown"),
"url": getattr(f, "server_relative_url", ""),
"current_size": current_size,
"version_count": version_count,
"total_version_size": total_version_size,
"storage_ratio": (total_version_size / current_size) if current_size > 0 else 0,
}
)
# Sort by version count descending
results.sort(key=lambda r: r["version_count"], reverse=True)
return results
def main():
parser = argparse.ArgumentParser(description="Analyze file version storage in a library")
parser.add_argument("--library", default="Shared Documents", help="document library to scan")
parser.add_argument(
"--threshold", type=int, default=_VERSION_THRESHOLD, help="version count that flags a cleanup candidate"
)
args = parser.parse_args()
print("Analyzing file version storage...\n")
ctx = ClientContext(site_url).with_username_and_password(
tenant=tenant, client_id=client_id, username=username, password=password
)
report = analyze_version_storage(ctx, args.library)
if not report:
print("No files found or library inaccessible.")
return
total_versions = sum(r["version_count"] for r in report)
total_storage = sum(r["total_version_size"] for r in report)
print(f"Files analyzed: {len(report)}")
print(f"Total versions: {total_versions}")
print(f"Version storage: {format_bytes(total_storage)}")
print()
# Top 10 files by version count
print("=== Top 10 files by version count ===\n")
print(f"{'File':50s} {'Versions':>10s} {'Version Size':>15s} {'Current Size':>15s} {'Ratio'}")
print("-" * 100)
for r in report[:10]:
print(
f"{r['name'][:48]:50s} "
f"{r['version_count']:>10d} "
f"{format_bytes(r['total_version_size']):>15s} "
f"{format_bytes(r['current_size']):>15s} "
f"{r['storage_ratio']:.1f}x"
)
# Files with excessive versions
excessive = [r for r in report if r["version_count"] >= args.threshold]
if excessive:
print(f"\n=== Files with {args.threshold}+ versions (cleanup candidates) ===\n")
for r in excessive:
print(f" {r['name']} — {r['version_count']} versions, {format_bytes(r['total_version_size'])}")
if __name__ == "__main__":
main()