# -*- coding: utf-8 -*-

# Copyright 2008-2016 Mir Calculate. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import sys
import re
from calculate.lib.cl_template import TemplateFormat
from calculate.lib.utils.files import process

from calculate.lib.cl_lang import setLocalTranslate

_ = lambda x: x
setLocalTranslate('cl_lib3', sys.modules[__name__])


class diff(TemplateFormat):
    """
    Format using diff
    """
    text = ""
    p1_token = re.compile(r'\n--- (.*)\n\+\+\+ ')

    def textToXML(self):
        return self.text

    def processingFile(self, textConfigFile, rootPath=None, nameFile=None):
        self.patchFiles = []
        # определить, что патч содержит только добавление новых файлов
        # удаляем b/ из целевого пути
        if all(x.group(1) == '/dev/null'
               for x in self.p1_token.finditer(self.text)):
            self.text = self.text.replace("--- /dev/null\n+++ b/",
                                          "--- /dev/null\n+++ ")
        for i in range(0, 4):
            patchDryRun = process('/usr/bin/patch', '--dry-run',
                                  '-p%d' % i, cwd=rootPath, )
            patchDryRun.write(self.text)
            if patchDryRun.success():
                break
            patchDryRun = process('/usr/bin/patch', '-R', '--dry-run',
                                  '-p%d' % i, cwd=rootPath, )
            patchDryRun.write(self.text)
            if patchDryRun.success():
                return ""
        else:
            self.setError(_("Correction failed"))
            return False
        patchRun = process('/usr/bin/patch',
                           '-p%d' % i, cwd=rootPath)
        patchRun.write(self.text)
        if patchRun.success():
            for line in patchRun:
                if line.startswith("patching file"):
                    self.patchFiles.append(line[13:].strip())
            return patchRun.read()
        return ""
