81 lines
2.4 KiB
Python
81 lines
2.4 KiB
Python
import difflib
|
|
from rest_framework.decorators import permission_classes
|
|
from adrf.views import APIView
|
|
from rest_framework.response import Response
|
|
from rest_framework import status
|
|
from rest_framework.permissions import AllowAny
|
|
|
|
|
|
@permission_classes([AllowAny])
|
|
class TextDiffView(APIView):
|
|
def post(self, request):
|
|
text_a = request.data.get('text_a')
|
|
text_b = request.data.get('text_b')
|
|
|
|
if text_a is None or text_b is None:
|
|
return Response(
|
|
{'error': 'text_a and text_b are required'},
|
|
status=status.HTTP_400_BAD_REQUEST,
|
|
)
|
|
|
|
lines_a = text_a.splitlines()
|
|
lines_b = text_b.splitlines()
|
|
|
|
diff_result = list(difflib.ndiff(lines_a, lines_b))
|
|
|
|
diff_lines = []
|
|
line_a = 0
|
|
line_b = 0
|
|
added_count = 0
|
|
removed_count = 0
|
|
unchanged_count = 0
|
|
|
|
for line in diff_result:
|
|
if line.startswith('? '):
|
|
continue
|
|
elif line.startswith('+ '):
|
|
line_b += 1
|
|
added_count += 1
|
|
diff_lines.append({
|
|
'line_number_a': None,
|
|
'line_number_b': line_b,
|
|
'type': 'added',
|
|
'content': line[2:],
|
|
})
|
|
elif line.startswith('- '):
|
|
line_a += 1
|
|
removed_count += 1
|
|
diff_lines.append({
|
|
'line_number_a': line_a,
|
|
'line_number_b': None,
|
|
'type': 'removed',
|
|
'content': line[2:],
|
|
})
|
|
elif line.startswith(' '):
|
|
line_a += 1
|
|
line_b += 1
|
|
unchanged_count += 1
|
|
diff_lines.append({
|
|
'line_number_a': line_a,
|
|
'line_number_b': line_b,
|
|
'type': 'unchanged',
|
|
'content': line[2:],
|
|
})
|
|
|
|
stats = {
|
|
'added_count': added_count,
|
|
'removed_count': removed_count,
|
|
'unchanged_count': unchanged_count,
|
|
'total_lines': len(diff_lines),
|
|
}
|
|
|
|
return Response(
|
|
{
|
|
'diff_lines': diff_lines,
|
|
'stats': stats,
|
|
'text_a_lines': len(lines_a),
|
|
'text_b_lines': len(lines_b),
|
|
},
|
|
status=status.HTTP_200_OK,
|
|
)
|