utils.py

1import os
2import sys
3import config
4import json
5import datetime
6
7def check_env(input):
8    return os.getenv(input, None)
9
10def check_env_expr(expression):
11    if expression.startswith("env:"):
12        return os.getenv(expression[4:], None)
13    return expression
14
15def readFile(file_path):
16    try:
17        if file_path.startswith("file:"):
18            file_path = file_path[5:]
19        with open(file_path, "r") as file:
20            return file.read().strip()
21    except FileNotFoundError:
22        print(f"File not found: {file_path}")
23        sys.exit(1)
24
25def toLower(input):
26    if input is not None:
27        return input.lower()
28    return None
29
30def doesStartWith(input, start):
31    if input is not None:
32        return input.startswith(start)
33    return False
34
35def read_credentials(file_path):
36    with open(file_path, "r") as file:
37        lines = file.readlines()
38
39    data = {}
40    current_section = None
41
42    for line in lines:
43        line = line.strip()
44        if line.startswith(":") and line.endswith(":"):
45            current_section = line[1:-1]
46            data[current_section] = {}
47        elif "=" in line and current_section:
48            key, value = line.split("=", 1)
49            value = value.strip()
50            if value.startswith("{") and value.endswith("}"):
51                if value.startswith("{env:"):
52                    value = check_env_expr(value[1:-1])
53                elif value.startswith("{file:"):
54                    value = readFile(value[1:-1])
55                else:
56                    print(f"Invalid expression: {value}")
57            if toLower(value) == "yes":
58                value = "true"
59            elif toLower(value) == "no":
60                value = "false"
61            data[current_section][key.strip()] = value
62
63    return data
64
65def get_config_names():
66    creds = read_credentials(config.account_dir)
67    return list(creds.keys())
68
69def get_account_login(name):
70    creds = read_credentials(config.account_dir)
71    account = creds[name]
72    return f"{account['user.name']} <{account['user.email']}> [{account['username']}]"
73
74def exists(data):
75    return data is not None and data != ""
76
77def has_gpg(data):
78    return (
79        exists(data.get("user.signingkey"))
80        or exists(data.get("commit.gpgSign"))
81        or exists(data.get("gpg.program"))
82    )
83
84def load(config_name):
85    creds = read_credentials(config.account_dir)
86    account = creds.get(config_name, {})
87
88    if not account:
89        print(f"No configuration found for {config_name}.")
90        return
91
92    gpg_signing_key = account.get("user.signingkey")
93    gpg_program = account.get("gpg.program")
94    gpg_sign = account.get("commit.gpgSign")
95
96    if gpg_signing_key or gpg_sign or gpg_program:
97        if not gpg_signing_key:
98            print(f"Warning: 'user.signingkey' is not set for {config_name}.")
99        if not gpg_sign:
100            print(f"Warning: 'commit.gpgSign' is not set for {config_name}.")
101        if not gpg_program:
102            print(f"Warning: 'gpg.program' is not set for {config_name}.")
103
104    print(f"Setting git config for {config_name}...")
105
106    template = f"""[credential]
107    helper = store
108[user]
109    email = {account['user.email']}
110    name = {account['user.name']}
111{f"    signingkey = {account['user.signingkey']}" if exists(account.get('user.signingkey')) else ""}
112[gpg]
113    program = {account.get('gpg.program', '/usr/bin/gpg')}
114[commit]
115    gpgSign = {account.get('commit.gpgSign', 'false')}
116    """
117
118    if not exists(account.get("username")):
119        print(f"Fatal: 'username' is not set for {config_name}.")
120        sys.exit(1)
121    if not exists(account.get("token")):
122        print(f"Fatal: 'token' is not set for {config_name}.")
123        sys.exit(1)
124
125    with open(config.get_git_config_path(), "w") as file:
126        file.write(template)
127
128    with open(config.get_git_credentials_path(), "w") as file:
129        file.write(f"https://{account['username']}:{account['token']}@github.com")
130
131    print(f"Configuration set for {config_name}.")
132    sys.exit(0)
133
134def create():
135    config_name = input("Please enter your Configuration Name: ")
136    user_name = input("Please enter your Git User Name: ")
137    user_email = input("Please enter your Git User Email: ")
138    user_signing_key = input("Do you have a GPG Signing Key? (yes/no): ").lower()
139    user_token = input("Please enter your GitHub Token: ")
140    user_username = input("Please enter your GitHub Username: ")
141
142    use_gpg = False
143    gpg_program = ""
144    gpg_sign = ""
145
146    if user_signing_key == "yes":
147        user_signing_key = input("Please enter your GPG Signing Key: ")
148        gpg_program = input("Please enter your GPG Program Path (Leave blank for default '/usr/bin/gpg'): ").strip()
149        gpg_sign = input("Do you want to sign your commits with GPG? (yes/no): ").lower()
150
151        if not gpg_program:
152            gpg_program = "/usr/bin/gpg"
153
154        use_gpg = True if gpg_sign == "yes" else False
155
156    template = f""":{config_name}:
157user.email={user_email}
158user.name={user_name}
159{f"user.signingkey={user_signing_key}" if use_gpg else ""}
160{f"gpg.program={gpg_program}" if use_gpg else ""}
161{f"commit.gpgSign={'Yes' if use_gpg else 'No'}" if use_gpg else ""}
162username={user_username}
163token={user_token}
164"""
165
166    try:
167        with open(config.account_dir, "a") as file:
168            file.write("\n")
169            file.write(template)
170        print(f"Configuration {config_name} created.")
171    except Exception as e:
172        print(f"An error occurred: {e}")
173
174def export():
175    config_name = input("Please enter the Configuration Name to export (Leave blank to export all): ")
176    creds = read_credentials(config.account_dir)
177    format = input("Please enter the format to export (json/txt): ").lower()
178
179    export_dir = input("Please enter the export directory (Leave blank for default './exports'): ")
180    
181    if not export_dir:
182        export_dir = "exports"
183
184    if not os.path.exists(export_dir):
185            os.mkdir(export_dir)
186
187   
188    
189
190    if config_name:
191        if format == "json":
192            with open(f"{export_dir}/{config_name}.json", "w") as file:
193                file.write(json.dumps(creds[config_name]))
194        elif format == "txt":
195            data = creds[config_name]
196            with open(f"{export_dir}/{config_name}.txt", "w") as file:
197                file.write(f":{config_name}:\n")
198                file.write(f"dataExportedOn={datetime.datetime.now().isoformat()}\n\n")
199                for key in data:
200                    file.write(f"{key}={data[key]}\n")
201        else:
202            print("Invalid format.")
203            sys.exit(1)
204    else:
205        if format == "json":
206            with open("{export_dir}/all.json", "w") as file:
207                file.write(json.dumps(creds))
208        elif format == "txt":
209            for key in creds:
210                data = creds[key]
211                with open(f"{export_dir}/{key}.txt", "w") as file:
212                    file.write(f":{key}:\n")
213                    file.write(f"dataExportedOn={datetime.datetime.now().isoformat()}\n\n")
214                    for key in data:
215                        file.write(f"{key}={data[key]}\n")
216        else:
217            print("Invalid format.")
218            sys.exit(1)
219        
220    print("Exported successfully.")
221
222
223        
224