function main_v10
Main entry point for a SharePoint to FileCloud synchronization application that handles command-line arguments, connection testing, and orchestrates single or continuous sync operations.
/tf/active/vicechatdev/SPFCsync/main.py
30 - 133
moderate
Purpose
This function serves as the CLI entry point for a document synchronization service between SharePoint and FileCloud. It parses command-line arguments to configure sync behavior (one-time vs continuous), test connections, load custom configuration files, and handle graceful shutdown via signal handlers. It provides detailed statistics output after sync operations and supports debugging features like document processing limits.
Source Code
def main():
"""Main entry point for the application."""
parser = argparse.ArgumentParser(
description="SharePoint to FileCloud Sync Application",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__
)
parser.add_argument(
'--once',
action='store_true',
help='Run sync once and exit (default: continuous)'
)
parser.add_argument(
'--config',
type=str,
help='Specify custom config file (default: .env)'
)
parser.add_argument(
'--test-connection',
action='store_true',
help='Test connections to SharePoint and FileCloud and exit'
)
parser.add_argument(
'--limit',
type=int,
help='Limit the number of documents to process (useful for debugging)'
)
args = parser.parse_args()
# Set up signal handler for graceful shutdown
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
try:
# Load custom config if specified
if args.config:
if not os.path.exists(args.config):
print(f"Error: Config file {args.config} not found")
sys.exit(1)
# Load the custom config file
os.environ['DOTENV_PATH'] = args.config
# Initialize the sync service
sync_service = SharePointFileCloudSync()
if args.test_connection:
print("Testing connections...")
print("✓ SharePoint connection successful")
print("✓ FileCloud connection successful")
print("All connections are working properly!")
return
if args.once:
# Run single sync
print("Running one-time synchronization...")
limit = args.limit if args.limit else None
if limit:
print(f"Processing limited to {limit} documents")
stats = sync_service.run_single_sync(max_documents=limit)
print("\nSync completed!")
print(f"Total documents: {stats['total_documents']}")
print(f"New uploads: {stats['new_uploads']}")
print(f"Updated files: {stats['updated_files']}")
if stats.get('updated_newer_source', 0) > 0:
print(f" └─ Updated (newer source): {stats['updated_newer_source']}")
print(f"Skipped files: {stats.get('skipped_files', 0) + stats.get('skipped_same_date', 0)}")
if stats.get('skipped_same_date', 0) > 0:
print(f" └─ Skipped (same date): {stats['skipped_same_date']}")
if stats.get('empty_folders_created', 0) > 0:
print(f"Empty folders created: {stats['empty_folders_created']}")
print(f"Errors: {stats['errors']}")
# Show percentage breakdown for large syncs
total = stats['total_documents']
if total > 100:
new_pct = (stats['new_uploads'] / total) * 100
updated_pct = (stats['updated_files'] / total) * 100
skipped_pct = ((stats.get('skipped_files', 0) + stats.get('skipped_same_date', 0)) / total) * 100
print(f"\nBreakdown: {new_pct:.1f}% new, {updated_pct:.1f}% updated, {skipped_pct:.1f}% skipped")
if stats['errors'] > 0:
sys.exit(1)
else:
# Run continuous sync
print("Starting continuous synchronization service...")
print(f"Sync interval: {Config.SYNC_INTERVAL_MINUTES} minutes")
limit = args.limit if args.limit else None
if limit:
print(f"Processing limited to {limit} documents per cycle")
print("Press Ctrl+C to stop")
sync_service.run_continuous_sync(max_documents=limit)
except KeyboardInterrupt:
print("\nSync service stopped by user")
except Exception as e:
logging.getLogger(__name__).error(f"Application error: {e}")
print(f"Error: {e}")
sys.exit(1)
Return Value
No explicit return value. The function exits with sys.exit(1) on errors or when error count is greater than 0, otherwise completes normally with implicit None return.
Dependencies
argparsesyssignaloslogging
Required Imports
import argparse
import sys
import signal
import os
import logging
from sync_service import SharePointFileCloudSync
from config import Config
Usage Example
# Run one-time sync
python script.py --once
# Run with custom config file
python script.py --config /path/to/custom.env --once
# Test connections only
python script.py --test-connection
# Run continuous sync with document limit for debugging
python script.py --limit 50
# Run one-time sync with limit
python script.py --once --limit 100
# Run continuous sync (default behavior)
python script.py
Best Practices
- Ensure signal_handler function is defined before calling main() to handle SIGINT and SIGTERM signals
- The SharePointFileCloudSync class must implement run_single_sync() and run_continuous_sync() methods with max_documents parameter support
- Config file should be validated before running sync operations
- Use --test-connection flag before running full sync to verify credentials and connectivity
- Use --limit parameter during initial testing to avoid processing large document sets
- Monitor the statistics output to track sync performance and identify issues
- The function expects stats dictionary from sync_service to contain keys: total_documents, new_uploads, updated_files, updated_newer_source, skipped_files, skipped_same_date, empty_folders_created, errors
- Custom config files specified with --config must exist or the application will exit with error code 1
- Application exits with code 1 if errors occur during sync, making it suitable for monitoring in production environments
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function main_v32 84.4% similar
-
function main_v37 78.3% similar
-
function main_v17 75.9% similar
-
class SharePointFileCloudSync 72.3% similar
-
function main_v16 71.9% similar