/ laxyfile / scripts / macos / build_app.py
swadhin biswas redy to jump in work · 7/25/2025
d8c49a5
410 lines · 12.6 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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#!/usr/bin/env python3
"""
macOS Application Bundle Builder for LaxyFile

This script creates a macOS .app bundle and optionally a DMG installer.
"""

import os
import sys
import shutil
import subprocess
from pathlib import Path
import plistlib
import json

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))


class MacOSAppBuilder:
    """macOS application bundle builder"""

    def __init__(self):
        self.project_root = Path(__file__).parent.parent.parent
        self.build_dir = self.project_root / 'build' / 'macos'
        self.dist_dir = self.project_root / 'dist' / 'macos'

        # App information
        self.app_name = "LaxyFile"
        self.app_version = "1.0.0"
        self.app_identifier = "com.laxyfile.LaxyFile"
        self.app_description = "Advanced terminal file manager with AI capabilities"
        self.app_author = "LaxyFile Team"
        self.app_copyright = "Copyright © 2024 LaxyFile Team"

        # Ensure build directories exist
        self.build_dir.mkdir(parents=True, exist_ok=True)
        self.dist_dir.mkdir(parents=True, exist_ok=True)

    def prepare_source(self):
        """Prepare source files for packaging"""
        print("Preparing source files...")

        # Copy LaxyFile source
        source_dir = self.project_root / 'laxyfile'
        target_dir = self.build_dir / 'laxyfile'

        if target_dir.exists():
            shutil.rmtree(target_dir)

        shutil.copytree(source_dir, target_dir)

        # Copy additional files
        additional_files = [
            'main.py',
            'run_laxyfile.py',
            'README.md',
            'LICENSE',
            'requirements.txt'
        ]

        for file_name in additional_files:
            source_file = self.project_root / file_name
            if source_file.exists():
                shutil.copy2(source_file, self.build_dir / file_name)

        print(f"Source prepared in: {self.build_dir}")

    def create_app_bundle(self):
        """Create macOS .app bundle"""
        print("Creating macOS app bundle...")

        app_bundle_dir = self.dist_dir / f"{self.app_name}.app"
        contents_dir = app_bundle_dir / 'Contents'
        macos_dir = contents_dir / 'MacOS'
        resources_dir = contents_dir / 'Resources'
        frameworks_dir = contents_dir / 'Frameworks'

        # Create directory structure
        for directory in [macos_dir, resources_dir, frameworks_dir]:
            directory.mkdir(parents=True, exist_ok=True)

        # Create Info.plist
        self._create_info_plist(contents_dir)

        # Copy application resources
        self._copy_app_resources(resources_dir)

        # Create executable script
        self._create_executable_script(macos_dir)

        # Copy Python dependencies (if needed)
        self._copy_python_dependencies(resources_dir)

        print(f"App bundle created: {app_bundle_dir}")
        return app_bundle_dir

    def _create_info_plist(self, contents_dir: Path):
        """Create Info.plist file"""
        info_plist = {
            'CFBundleDevelopmentRegion': 'en',
            'CFBundleExecutable': self.app_name.lower(),
            'CFBundleIdentifier': self.app_identifier,
            'CFBundleInfoDictionaryVersion': '6.0',
            'CFBundleName': self.app_name,
            'CFBundleDisplayName': self.app_name,
            'CFBundlePackageType': 'APPL',
            'CFBundleShortVersionString': self.app_version,
            'CFBundleVersion': self.app_version,
            'CFBundleSignature': 'LXYF',
            'LSMinimumSystemVersion': '10.12',
            'NSHighResolutionCapable': True,
            'NSSupportsAutomaticGraphicsSwitching': True,
            'LSApplicationCategoryType': 'public.app-category.utilities',
            'NSHumanReadableCopyright': self.app_copyright,

            # Document types
            'CFBundleDocumentTypes': [
                {
                    'CFBundleTypeRole': 'Viewer',
                    'CFBundleTypeName': 'Folder',
                    'LSHandlerRank': 'Alternate',
                    'LSItemContentTypes': ['public.folder']
                }
            ],

            # URL schemes (if needed)
            'CFBundleURLTypes': [
                {
                    'CFBundleURLName': self.app_identifier,
                    'CFBundleURLSchemes': ['laxyfile']
                }
            ]
        }

        # Add icon if available
        icon_file = self.project_root / 'assets' / 'icon.icns'
        if icon_file.exists():
            info_plist['CFBundleIconFile'] = 'icon.icns'

        plist_file = contents_dir / 'Info.plist'
        with open(plist_file, 'wb') as f:
            plistlib.dump(info_plist, f)

        print(f"Created Info.plist: {plist_file}")

    def _copy_app_resources(self, resources_dir: Path):
        """Copy application resources"""
        # Copy LaxyFile source
        shutil.copytree(self.build_dir / 'laxyfile', resources_dir / 'laxyfile')

        # Copy additional files
        for file_name in ['README.md', 'LICENSE']:
            source_file = self.build_dir / file_name
            if source_file.exists():
                shutil.copy2(source_file, resources_dir / file_name)

        # Copy icon if available
        icon_file = self.project_root / 'assets' / 'icon.icns'
        if icon_file.exists():
            shutil.copy2(icon_file, resources_dir / 'icon.icns')

        print(f"Copied resources to: {resources_dir}")

    def _create_executable_script(self, macos_dir: Path):
        """Create executable script"""
        executable_script = macos_dir / self.app_name.lower()

        script_content = f'''#!/bin/bash

# Get the directory containing this script
DIR="$( cd "$( dirname "${{BASH_SOURCE[0]}}" )" && pwd )"
RESOURCES_DIR="$DIR/../Resources"

# Set up environment
export PYTHONPATH="$RESOURCES_DIR:$PYTHONPATH"
export LAXYFILE_BUNDLE=1

# Change to resources directory
cd "$RESOURCES_DIR"

# Run LaxyFile
exec {shutil.which('python3') or 'python3'} -m laxyfile "$@"
'''

        executable_script.write_text(script_content)
        executable_script.chmod(0o755)

        print(f"Created executable: {executable_script}")

    def _copy_python_dependencies(self, resources_dir: Path):
        """Copy Python dependencies (optional)"""
        # This would copy Python dependencies if creating a standalone bundle
        # For now, we assume Python is installed on the system

        # Create a requirements file for easy installation
        requirements_content = '''# LaxyFile dependencies
rich>=13.0.0
click>=8.0.0
pyyaml>=6.0
watchdog>=3.0.0
python-magic>=0.4.27
pillow>=9.0.0
pygments>=2.14.0
'''

        requirements_file = resources_dir / 'requirements.txt'
        requirements_file.write_text(requirements_content)

        # Create installation script
        install_script = resources_dir / 'install_dependencies.sh'
        install_content = '''#!/bin/bash
echo "Installing LaxyFile dependencies..."
pip3 install -r requirements.txt
echo "Dependencies installed successfully!"
'''
        install_script.write_text(install_content)
        install_script.chmod(0o755)

    def create_dmg(self, app_bundle_path: Path):
        """Create DMG installer"""
        print("Creating DMG installer...")

        dmg_name = f"{self.app_name}-{self.app_version}"
        dmg_path = self.dist_dir / f"{dmg_name}.dmg"

        # Remove existing DMG
        if dmg_path.exists():
            dmg_path.unlink()

        # Create temporary DMG directory
        dmg_temp_dir = self.build_dir / 'dmg_temp'
        if dmg_temp_dir.exists():
            shutil.rmtree(dmg_temp_dir)
        dmg_temp_dir.mkdir()

        # Copy app bundle to temp directory
        shutil.copytree(app_bundle_path, dmg_temp_dir / f"{self.app_name}.app")

        # Create Applications symlink
        applications_link = dmg_temp_dir / 'Applications'
        applications_link.symlink_to('/Applications')

        # Copy additional files
        readme_content = f'''# {self.app_name} {self.app_version}

{self.app_description}

## Installation

1. Drag {self.app_name}.app to the Applications folder
2. Open Terminal and run the dependency installer:
   ```
   /Applications/{self.app_name}.app/Contents/Resources/install_dependencies.sh
   ```
3. Launch {self.app_name} from Applications or Spotlight

## Requirements

- macOS 10.12 or later
- Python 3.8 or later
- Xcode Command Line Tools (for some dependencies)

## Support

For support and documentation, visit: https://github.com/user/laxyfile
'''

        readme_file = dmg_temp_dir / 'README.txt'
        readme_file.write_text(readme_content)

        # Create DMG using hdiutil
        try:
            subprocess.run([
                'hdiutil', 'create',
                '-volname', dmg_name,
                '-srcfolder', str(dmg_temp_dir),
                '-ov',
                '-format', 'UDZO',
                str(dmg_path           ], check=True)

            print(f"DMG created: {dmg_path}")
            return dmg_path

        except subprocess.CalledProcessError as e:
            print(f"Failed to create DMG: {e}")
            return None

        finally:
            # Clean up temp directory
            if dmg_temp_dir.exists():
                shutil.rmtree(dmg_temp_dir)

    def create_homebrew_formula(self):
        """Create Homebrew formula"""
        print("Creating Homebrew formula...")

        formula_dir = self.dist_dir / 'homebrew'
        formula_dir.mkdir(exist_ok=True)

        formula_content = f'''class Laxyfile < Formula
  desc "{self.app_description}"
  homepage "https://github.com/user/laxyfile"
  url "https://github.com/user/laxyfile/archive/v{self.app_version}.tar.gz"
  sha256 "0000000000000000000000000000000000000000000000000000000000000000"  # Update with actual SHA256
  license "MIT"

  depends_on "[email protected]"

  def install
    # Install Python dependencies
    system Formula["[email protected]"].opt_bin/"pip3", "install", "-r", "requirements.txt", "--prefix=\#{prefix}"

    # Install LaxyFile
    libexec.install Dir["*"]

    # Create wrapper script
    (bin/"laxyfile").write <<~EOS
      #!/bin/bash
      export PYTHONPATH="\#{libexec}:\#{Formula["[email protected]"].opt_lib}/python3.11/site-packages:$PYTHONPATH"
      cd "\#{libexec}"
      exec "\#{Formula["[email protected]"].opt_bin}/python3" -m laxyfile "$@"
    EOS
  end

  test do
    system bin/"laxyfile", "--version"
  end
end
'''

        formula_file = formula_dir / 'laxyfile.rb'
        formula_file.write_text(formula_content)

        print(f"Homebrew formula created: {formula_file}")
        print("To use:")
        print(f"  brew install {formula_file}")

        return formula_file

    def build_all(self):
        """Build all macOS packages"""
        print(f"Building macOS packages for {self.app_name} {self.app_version}")
        print()

        # Prepare source
        self.prepare_source()

        packages = []

        # Create app bundle
        try:
            app_bundle = self.create_app_bundle()
            packages.append(('App Bundle', app_bundle))
        except Exception as e:
            print(f"App bundle creation failed: {e}")
            return packages

        # Create DMG
        try:
            dmg_file = self.create_dmg(app_bundle)
            if dmg_file:
                packages.append(('DMG Installer', dmg_file))
        except Exception as e:
            print(f"DMG creation failed: {e}")

        # Create Homebrew formula
        try:
            formula_file = self.create_homebrew_formula()
            packages.append(('Homebrew Formula', formula_file))
        except Exception as e:
            print(f"Homebrew formula creation failed: {e}")

        print()
        print("macOS package build complete!")
        print("Created packages:")
        for package_type, package_file in packages:
            print(f"  {package_type}: {package_file}")

        return packages


def main():
    """Main entry point"""
    import argparse

    parser = argparse.ArgumentParser(description='Build macOS packages for LaxyFile')
    parser.add_argument('--app-only', action='store_true', help='Build app bundle only')
    parser.add_argument('--dmg-only', action='store_true', help='Build DMG only')
    parser.add_argument('--homebrew-only', action='store_true', help='Create Homebrew formula only')

    args = parser.parse_args()

    builder = MacOSAppBuilder()

    if args.app_only:
        builder.prepare_source()
        builder.create_app_bundle()
    elif args.dmg_only:
        builder.prepare_source()
        app_bundle = builder.create_app_bundle()
        builder.create_dmg(app_bundle)
    elif args.homebrew_only:
        builder.create_homebrew_formula()
    else:
        builder.build_all()


if __name__ == '__main__':
    main()