extensions.py 4.9 KB
Newer Older
1 2 3 4
import os
import sys
import traceback

5
import time
6 7
import git

8
from modules import shared
A
AUTOMATIC 已提交
9
from modules.paths_internal import extensions_dir, extensions_builtin_dir, script_path  # noqa: F401
10 11 12

extensions = []

13 14 15
if not os.path.exists(extensions_dir):
    os.makedirs(extensions_dir)

16 17

def active():
18 19 20 21 22 23
    if shared.opts.disable_all_extensions == "all":
        return []
    elif shared.opts.disable_all_extensions == "extra":
        return [x for x in extensions if x.enabled and x.is_builtin]
    else:
        return [x for x in extensions if x.enabled]
24 25 26


class Extension:
A
AUTOMATIC 已提交
27
    def __init__(self, name, path, enabled=True, is_builtin=False):
28 29 30 31 32
        self.name = name
        self.path = path
        self.enabled = enabled
        self.status = ''
        self.can_update = False
A
AUTOMATIC 已提交
33
        self.is_builtin = is_builtin
34 35
        self.commit_hash = ''
        self.commit_date = None
36
        self.version = ''
37
        self.branch = None
38 39 40 41
        self.remote = None
        self.have_info_from_repo = False

    def read_info_from_repo(self):
42
        if self.is_builtin or self.have_info_from_repo:
43 44 45
            return

        self.have_info_from_repo = True
46 47 48

        repo = None
        try:
49 50
            if os.path.exists(os.path.join(self.path, ".git")):
                repo = git.Repo(self.path)
51
        except Exception:
52
            print(f"Error reading github repository info from {self.path}:", file=sys.stderr)
53 54 55 56 57
            print(traceback.format_exc(), file=sys.stderr)

        if repo is None or repo.bare:
            self.remote = None
        else:
58 59
            try:
                self.status = 'unknown'
60
                self.remote = next(repo.remote().urls, None)
61
                head = repo.head.commit
62 63 64 65 66 67 68 69 70
                self.commit_date = repo.head.commit.committed_date
                ts = time.asctime(time.gmtime(self.commit_date))
                if repo.active_branch:
                    self.branch = repo.active_branch.name
                self.commit_hash = head.hexsha
                self.version = f'{self.commit_hash[:8]} ({ts})'

            except Exception as ex:
                print(f"Failed reading extension data from Git repository ({self.name}): {ex}", file=sys.stderr)
71
                self.remote = None
72 73 74 75 76 77 78 79 80 81

    def list_files(self, subdir, extension):
        from modules import scripts

        dirpath = os.path.join(self.path, subdir)
        if not os.path.isdir(dirpath):
            return []

        res = []
        for filename in sorted(os.listdir(dirpath)):
82
            res.append(scripts.ScriptFile(self.path, filename, os.path.join(dirpath, filename)))
83 84 85 86 87 88 89

        res = [x for x in res if os.path.splitext(x.path)[1].lower() == extension and os.path.isfile(x.path)]

        return res

    def check_updates(self):
        repo = git.Repo(self.path)
A
Adam Huganir 已提交
90
        for fetch in repo.remote().fetch(dry_run=True):
91 92
            if fetch.flags != fetch.HEAD_UPTODATE:
                self.can_update = True
93
                self.status = "new commits"
94 95
                return

96 97 98 99 100 101 102 103 104 105 106
        try:
            origin = repo.rev_parse('origin')
            if repo.head.commit != origin:
                self.can_update = True
                self.status = "behind HEAD"
                return
        except Exception:
            self.can_update = False
            self.status = "unknown (remote error)"
            return

107 108 109
        self.can_update = False
        self.status = "latest"

110
    def fetch_and_reset_hard(self, commit='origin'):
111
        repo = git.Repo(self.path)
112 113
        # Fix: `error: Your local changes to the following files would be overwritten by merge`,
        # because WSL2 Docker set 755 file permissions instead of 644, this results to the error.
A
Adam Huganir 已提交
114
        repo.git.fetch(all=True)
115
        repo.git.reset(commit, hard=True)
116
        self.have_info_from_repo = False
117 118 119 120 121


def list_extensions():
    extensions.clear()

122
    if not os.path.isdir(extensions_dir):
123 124
        return

125
    if shared.opts.disable_all_extensions == "all":
126
        print("*** \"Disable all extensions\" option was set, will not load any extensions ***")
127 128
    elif shared.opts.disable_all_extensions == "extra":
        print("*** \"Disable all extensions\" option was set, will only load built-in extensions ***")
129

130
    extension_paths = []
131
    for dirname in [extensions_dir, extensions_builtin_dir]:
A
AUTOMATIC 已提交
132 133
        if not os.path.isdir(dirname):
            return
134

A
AUTOMATIC 已提交
135 136 137 138 139
        for extension_dirname in sorted(os.listdir(dirname)):
            path = os.path.join(dirname, extension_dirname)
            if not os.path.isdir(path):
                continue

140
            extension_paths.append((extension_dirname, path, dirname == extensions_builtin_dir))
A
AUTOMATIC 已提交
141

142
    for dirname, path, is_builtin in extension_paths:
A
AUTOMATIC 已提交
143
        extension = Extension(name=dirname, path=path, enabled=dirname not in shared.opts.disabled_extensions, is_builtin=is_builtin)
144
        extensions.append(extension)