File size: 4,067 Bytes
a7d7463
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""File Operations Utility"""

import os
import shutil
import json
from pathlib import Path
from typing import List, Optional, Dict, Any
from datetime import datetime


class FileOps:
    """File operation utilities"""

    @staticmethod
    def read_text(file_path: str, encoding: str = "utf-8") -> str:
        """Read text content from file"""
        with open(file_path, "r", encoding=encoding) as f:
            return f.read()

    @staticmethod
    def write_text(file_path: str, content: str, encoding: str = "utf-8"):
        """Write text content to file"""
        Path(file_path).parent.mkdir(parents=True, exist_ok=True)
        with open(file_path, "w", encoding=encoding) as f:
            f.write(content)

    @staticmethod
    def read_json(file_path: str) -> Dict[str, Any]:
        """Read JSON file"""
        with open(file_path, "r", encoding="utf-8") as f:
            return json.load(f)

    @staticmethod
    def write_json(file_path: str, data: Dict[str, Any], indent: int = 2):
        """Write JSON file"""
        Path(file_path).parent.mkdir(parents=True, exist_ok=True)
        with open(file_path, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=indent, ensure_ascii=False)

    @staticmethod
    def append_jsonl(file_path: str, data: Dict[str, Any]):
        """Append data as JSONL line"""
        Path(file_path).parent.mkdir(parents=True, exist_ok=True)
        with open(file_path, "a", encoding="utf-8") as f:
            f.write(json.dumps(data, ensure_ascii=False) + "\n")

    @staticmethod
    def read_jsonl(file_path: str) -> List[Dict[str, Any]]:
        """Read JSONL file"""
        results = []
        with open(file_path, "r", encoding="utf-8") as f:
            for line in f:
                if line.strip():
                    results.append(json.loads(line))
        return results

    @staticmethod
    def list_files(directory: str, pattern: str = "*") -> List[Path]:
        """List files in directory matching pattern"""
        return list(Path(directory).glob(pattern))

    @staticmethod
    def create_directory(path: str):
        """Create directory if it doesn't exist"""
        Path(path).mkdir(parents=True, exist_ok=True)

    @staticmethod
    def delete_file(path: str):
        """Delete file"""
        Path(path).unlink(missing_ok=True)

    @staticmethod
    def copy_file(src: str, dst: str):
        """Copy file"""
        Path(dst).parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(src, dst)

    @staticmethod
    def move_file(src: str, dst: str):
        """Move file"""
        Path(dst).parent.mkdir(parents=True, exist_ok=True)
        shutil.move(src, dst)

    @staticmethod
    def get_file_info(path: str) -> Dict[str, Any]:
        """Get file information"""
        p = Path(path)
        stat = p.stat()

        return {
            "path": str(p.absolute()),
            "name": p.name,
            "size": stat.st_size,
            "modified": datetime.fromtimestamp(stat.st_mtime).isoformat(),
            "is_file": p.is_file(),
            "is_dir": p.is_dir(),
        }

    @staticmethod
    def find_files(directory: str, extensions: List[str]) -> List[Path]:
        """Find files with specific extensions"""
        results = []
        for ext in extensions:
            results.extend(Path(directory).rglob(f"*.{ext}"))
        return results

    @staticmethod
    def get_directory_size(path: str) -> int:
        """Calculate directory size in bytes"""
        total = 0
        for p in Path(path).rglob("*"):
            if p.is_file():
                total += p.stat().st_size
        return total

    @staticmethod
    def clean_directory(path: str, keep_pattern: Optional[str] = None):
        """Clean directory, optionally keeping files matching pattern"""
        for item in Path(path).iterdir():
            if keep_pattern and item.match(keep_pattern):
                continue
            if item.is_file():
                item.unlink()
            elif item.is_dir():
                shutil.rmtree(item)