🔍 Code Extractor

function main_v9

Maturity: 46

Main entry point for a SharePoint to FileCloud synchronization application that handles command-line arguments, connection testing, and orchestrates single or continuous sync operations.

File:
/tf/active/vicechatdev/SPFCsync/main.py
Lines:
30 - 133
Complexity:
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

  • argparse
  • sys
  • signal
  • os
  • logging

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
if __name__ == '__main__':
    main()

# Command-line usage examples:
# python script.py --once
# python script.py --test-connection
# python script.py --config custom_config.env --once
# python script.py --limit 50 --once
# python script.py  # Runs continuous sync

Best Practices

  • Always ensure signal_handler function is defined before calling main() to handle graceful shutdowns
  • Use --test-connection flag before running full sync to verify connectivity
  • Use --limit parameter during initial testing to avoid processing large document sets
  • Ensure proper environment variables or config file is set up before running
  • Monitor the statistics output to track sync performance and identify issues
  • Use --once flag for scheduled/cron jobs instead of continuous mode
  • Custom config files specified with --config must exist or the application will exit with error code 1
  • The function sets up SIGINT and SIGTERM handlers for graceful shutdown in continuous mode

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function main_v18 85.2% similar

    Command-line interface entry point for monitoring SharePoint to FileCloud synchronization logs, providing status analysis, log tailing, and real-time watching capabilities.

    From: /tf/active/vicechatdev/SPFCsync/monitor.py
  • function main_v8 79.1% similar

    Main test function that validates SharePoint Graph API integration, tests the Graph client connection, and verifies FileCloud sync functionality.

    From: /tf/active/vicechatdev/SPFCsync/test_graph_client.py
  • function main_v21 75.6% similar

    Orchestrates and executes a comprehensive test suite for SharePoint to FileCloud synchronization service, running configuration, connection, and operation tests.

    From: /tf/active/vicechatdev/SPFCsync/test_connections.py
  • function main_v11 74.1% similar

    Executes a diagnostic analysis for file synchronization issues, analyzes missing files, and saves the results to a JSON file.

    From: /tf/active/vicechatdev/SPFCsync/deep_diagnostics.py
  • class SharePointFileCloudSync 72.6% similar

    Orchestrates synchronization of documents from SharePoint to FileCloud, managing the complete sync lifecycle including document retrieval, comparison, upload, and folder structure creation.

    From: /tf/active/vicechatdev/SPFCsync/sync_service.py
← Back to Browse