-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit_diff.py
More file actions
320 lines (242 loc) · 8.96 KB
/
git_diff.py
File metadata and controls
320 lines (242 loc) · 8.96 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
"""
Script Name: git_diff.py
Description:
This script provides a command-line utility to visually compare changes
between two Git revisions using the Meld diff tool. It automates the process
of extracting file contents from specified Git revisions, saving them to
temporary directories, and launching Meld for side-by-side comparison.
Features:
- Parses command-line arguments for customization (Meld path, repo path, revisions, etc.)
- Extracts changed files between two Git revisions
- Saves file versions to separate directories for comparison
- Supports symbolic linking for current HEAD files
- Handles logging with customizable log levels and directories
- Robust error handling and logging
Usage:
python git_diff.py [rev_old] [rev_new]
Options:
--meld-exec Path to Meld executable (default: 'meld')
--dir-repo Path to the git repository (default: current directory)
--dir-old Directory for older revision files
--dir-new Directory for newer revision files
--log-dir Directory to save logs
--rev-old Older git revision (default: 'HEAD^')
--rev-new Newer git revision (default: 'HEAD')
--log-level Logging level (default: 'debug')
Dependencies:
- Python 3.x
- Meld diff tool
- logger.py (custom logging module)
Author:
Andrii Dov.
Date:
20260202
"""
import argparse
import os
import shutil
import subprocess
import sys
import traceback
from logger import Logger
# Default values, to customize:
LOG_LEVEL = 'debug'
MELD_EXEC = 'meld'
COMPARE_DIR = '/home/user/temp/compare'
CMP_OLD_DIR = f'{COMPARE_DIR}/old'
CMP_NEW_DIR = f'{COMPARE_DIR}/new'
GIT_OLD_REV = 'HEAD^'
GIT_NEW_REV = 'HEAD'
# Global variables
LOG = None
def get_argparser():
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument('--meld-exec'
, help='path to Meld executable application' \
f'default value for this argument is: {MELD_EXEC}'
, default=MELD_EXEC
, type=str)
parser.add_argument('--dir-repo'
, help='The path to the git repository' \
f'default value for this argument is the directory you are staying in'
, default=os.getcwd().replace('\\', '/')
, type=str)
parser.add_argument('--dir-old'
, help='Older version of git files' \
f'default value for this argument is: {CMP_OLD_DIR}'
, default=CMP_OLD_DIR
, type=str)
parser.add_argument('--dir-new'
, help='Newer version of git files' \
f'default value for this argument is: {CMP_NEW_DIR}'
, default=CMP_NEW_DIR
, type=str)
parser.add_argument('--log-dir'
, help='Directory to save logs. ' \
'File log won\'t be created in case directory is not settled'
, type=str)
parser.add_argument('--rev-old'
, help='Older revision, could be passed as unnamed param 0' \
f'default value for this argument is: {GIT_OLD_REV}'
, default=GIT_OLD_REV
, type=str)
parser.add_argument('--rev-new'
, help='Older revision, could be passed as unnamed param 1' \
f'default value for this argument is: {GIT_NEW_REV}'
, default=GIT_NEW_REV
, type=str)
parser.add_argument('--log-level'
, help=f'Directory to save logs. Default value is: {LOG_LEVEL}'
, default=LOG_LEVEL
, type=str)
return parser
# PRIVATE VARIABLES AND FUNCTIONS
RUN_COMMANDS = {
"git_get_root_dir" : {
"cmd": "git",
"arg_list": [
"rev-parse", "--show-toplevel"
],
"active_dir": "{dir_repo}"
},
"git_get_diff_rev_files": {
"cmd": "git",
"arg_list": [ "diff", "--name-only", "{rev_old}..{rev_new}" ]
},
"git_get_file_content_at_revision": {
"cmd": "git",
"arg_list": [ "show", "{revision}:{git_file}" ]
},
"run_diff": {
"cmd": "{meld_exec}",
"arg_list": [ "{dir_old}", "{dir_new}" ]
}
}
def __run_command(command_name, **kwargs):
class Log:
def __init__(self, **kwargs):
self.quiet = False
if "quiet" in kwargs:
self.quiet = kwargs["quiet"]
def info(self, str):
if not self.quiet:
LOG.info(str)
def debug(self, str):
if not self.quiet:
LOG.debug(str)
def dbg(self, str):
if not self.quiet:
LOG.dbg(str)
log = Log(**kwargs)
cmd_node = RUN_COMMANDS[command_name]
command = [cmd_node['cmd'].format(**kwargs)]
for arg in cmd_node['arg_list']:
command.append(arg.format(**kwargs))
log.info(f"Running command: {' '.join(command)}")
output_str = ""
p = subprocess.Popen(command,
shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
output_str += line.decode("utf-8", 'ignore')
retval = p.wait()
return (retval, output_str)
def __write_to_file(file, content):
if content == None:
return
os.makedirs(os.path.dirname(file), exist_ok=True)
with open(file, "wb") as f:
f.write(content.encode('utf-8'))
def __save_files(args, files_str):
for file in files_str.splitlines():
prev_file_name = "{}/{}".format(args.dir_old, file)
curr_file_name = "{}/{}".format(args.dir_new, file)
prev_content = None
curr_content = None
res = __run_command("git_get_file_content_at_revision"
, revision=args.rev_old, git_file=file, quiet=True)
if res[0] == 0:
prev_content = res[1]
__write_to_file(prev_file_name, prev_content)
src_file = f'{args.dir_repo}/{file}'
if args.rev_new == 'HEAD' and os.path.isfile(src_file):
# create a symbolic link file for current version
lnk_file = f'{args.dir_new}/{file}'
if not os.path.isfile(lnk_file):
os.makedirs(os.path.dirname(lnk_file), exist_ok=True)
os.link(src_file, lnk_file)
else:
LOG.warning(f'file already exists: {lnk_file}, skipped')
else:
res = __run_command("git_get_file_content_at_revision"
, revision=args.rev_new, git_file=file, quiet=True)
if res[0] == 0:
curr_content = res[1]
__write_to_file(curr_file_name, curr_content)
curr_status = ' ' if os.path.isfile(f'{args.dir_new}/{file}') else 'D'
perv_status = ' ' if os.path.isfile(f'{args.dir_old}/{file}') else 'C'
LOG.info("{}{} | {}".format(perv_status, curr_status, file))
# PUBLIC FUNTIONS
def do_argparse():
parser = get_argparser()
return parser.parse_known_args()
def extend_arguments_list(args, other_args):
if len(other_args) == 1:
args.rev_new = other_args[0]
args.rev_old = other_args[0] + '~1'
elif len(other_args) == 2:
args.rev_old = other_args[0]
args.rev_new = other_args[1]
# it's better to see revisions as a directory name
args.dir_new = '{}/{}'.format(COMPARE_DIR,
args.rev_new.replace('~', '-').replace('^', '-'))
args.dir_old = '{}/{}'.format(COMPARE_DIR,
args.rev_old.replace('~', '-').replace('^', '-'))
# LOG should be inited
setattr(args, 'log', Logger(args=args))
global LOG
LOG = args.log
LOG.debug(f'script settings:\nargs = {args}\nother_args = {other_args}')
def git_df_init(args):
if os.path.isdir(COMPARE_DIR):
LOG.info(f'Remove previous compare directory directory: {COMPARE_DIR}')
shutil.rmtree(COMPARE_DIR)
LOG.debug(f'{COMPARE_DIR} was deleted')
# create new directories
for dir in [args.dir_old, args.dir_new]:
LOG.info(f'Creating directory: {dir}')
os.makedirs(dir, exist_ok=True)
def git_df_diff(args):
def run_n_check(cmd):
res, out = __run_command(cmd, **vars(args))
if res:
raise RuntimeError(
f"Command: {cmd}\n\thas failed with code {res}\n\terror: {out}")
return out
args.dir_repo = run_n_check('git_get_root_dir').strip()
files_list = run_n_check('git_get_diff_rev_files')
__save_files(args, files_list)
__run_command('run_diff', **vars(args))
def git_df_run(args):
LOG.info("df - Show git changes between two versions")
git_df_init(args)
git_df_diff(args)
LOG.info("df - Show git changes between two versions: done.")
def main():
(args, other_args) = do_argparse()
extend_arguments_list(args, other_args)
try:
git_df_run(args)
except Exception as e:
if hasattr(e, 'message'):
LOG.error(e.message)
else:
LOG.error(e)
error_text = 'Error: {}'.format(traceback.format_exc())
LOG.error(error_text)
LOG.critical('Terminated due critical error')
sys.exit(1)
if __name__ == "__main__":
main()