Exemplo n.º 1
0
class RepertoireModel:
    def __init__(self):
        self.processDirectory = True
        self.num_operations = 0
        self.operations_so_far = IntegerWrapper(0)
        self.ccfx = CCFXEntryPoint('../ccFinder/ccfx',40,True,True)
        self.flags = {"No":True, "Yes":False}

    def setDiffPaths(self, path0 = None, path1 = None):
        path0 = str(path0)
        path1 = str(path1)
        if (not os.path.isdir(path0) or
            not os.path.isdir(path1)):
            return False
        self.paths = {'proj0':path0, 'proj1':path1}
        return True

    def setDiffPaths(self, path0 = None, path1 = None, isDirectory = True):
        path0 = str(path0)
        path1 = str(path1)
        
        self.ccfx.isDirectory = self.processDirectory = isDirectory
        if (isDirectory is True) and (not os.path.isdir(path0) or
            not os.path.isdir(path1)):
            return False
        elif (isDirectory is False) and (not os.path.isfile(path0) or
            not os.path.isfile(path1)):
            return False
        self.paths = {'proj0':path0, 'proj1':path1}
        return True

    def setTmpDirectory(self, path):
        path = str(path)
        if not os.path.isdir(path):
            return False
        # great, we have a scratch space, lets put our own directory there
        # so we know we probably aren't going to fight someone else for names
        uniq = 'repertoire_tmp_' + str(int(os.times()[4] * 100))
        tmpPath = path + os.sep + uniq
        os.mkdir(tmpPath)
        self.tmpPath = tmpPath
        return True

    def setSuffixes(self, jSuff = '', cSuff = '', hSuff = ''):
        jSuff = str(jSuff)
        cSuff = str(cSuff)
        hSuff = str(hSuff)
        if jSuff.startswith('.'):
            jSuff = jSuff[1:]
        if cSuff.startswith('.'):
            cSuff = cSuff[1:]
        if hSuff.startswith('.'):
            hSuff = hSuff[1:]
        self.suffixes = {
                'java':jSuff,
                'cxx':cSuff,
                'hxx':hSuff,
                }
        self.filters = {
                'java' : DiffFilter(jSuff),
                'cxx'  : DiffFilter(cSuff),
                'hxx'  : DiffFilter(hSuff)
                }

    def setCcfxDirectory(self, path):
        path = str(path)
        if not os.path.isdir(path):
            return False
        ccfx_binary = path + "/ccfx"
        if os.path.exists(ccfx_binary):
            self.ccfx.ccfxPath = ccfx_binary
            return True
        return False

    def setCcfxToken(self, token_size):
        self.ccfx.tokenSize = token_size
        print "setting ccFinder token size = " + token_size
        return True

    def setCcfxFileSeparator(self, flag):
        self.ccfx.fileSep = self.flags[str(flag)]
        print "setting ccFinder file separator flag to %d" % (self.ccfx.fileSep)
        return True

    def setCcfxGroupSeparator(self, flag):
        self.ccfx.grpSep = self.flags[str(flag)]
        print "setting ccFinder group separator flag to %d" % (self.ccfx.grpSep)
        return True


    def filterDiffProjs(self, interface):
      # 3 different file formats, 2 operations each (filter/convert)     
        self.num_operations = len(os.listdir(self.paths['proj0'])) * 3 * 2
        if self.paths['proj0'] != self.paths['proj1']:
            self.num_operations += len(os.listdir(self.paths['proj1'])) * 3 * 2
        self.num_operations += 2*6 #2 ccFinder call for all 6 output files
        self.operations_so_far = IntegerWrapper(0)

        for proj in ['proj0', 'proj1']:
            for lang in ['java', 'cxx', 'hxx']:
                the_filter = self.filters[lang]
                for i, file_name in enumerate(os.listdir(self.paths[proj])):
                    if interface.cancelled():
                        return ('User cancelled processing', False)
                    interface.progress('Filtering {0} files'.format(lang),
                            self.operations_so_far.value / float(self.num_operations))
                    input_path = self.paths[proj] + os.sep + file_name
#                    out_path = (self.pb.getFilterOutputPath(proj, lang) +
#                            ('%04d' % i) + '.' + self.suffixes[lang])
                    out_path = (self.pb.getFilterOutputPath(proj, lang) +
                            file_name + '.' + self.suffixes[lang])
                    (ok, gotsome) = the_filter.filterDiff(input_path, out_path)
                    # this is actually tricky, if we got some output for java
                    # in one project but not the other, then we know that
                    # there can't be any clones
                    self.got_some[lang] = self.got_some[lang] and gotsome
                    if not ok:
                        return ('Error processing: ' + file_name, False)
                    self.operations_so_far.incr()
            if self.paths['proj0'] == self.paths['proj1']:
                print "filterDiffProjs: two paths same, breaking!!"
                break

    
    def filterDiffFiles(self, interface):
        # 3 different file formats, 2 operations each (filter/convert)
        self.num_operations =  3 * 2
        if self.paths['proj0'] != self.paths['proj1']:
            self.num_operations += 3 * 2
        self.operations_so_far = IntegerWrapper(0)

        input_file1 = self.paths['proj0']
        input_file2 = self.paths['proj1']
        lang1 = os.path.splitext(input_file1)[1] #extension
        lang2 = os.path.splitext(input_file2)[1] #extension

        if lang1 != lang2 :
            print "!!the two files have different extension"
            print "lang1 = " + lang1
            print "lang2 = " + lang2
            return False

        for proj in ['proj0', 'proj1']:
            for lang in ['java', 'cxx', 'hxx']:
                the_filter = self.filters[lang]
                if interface.cancelled():
                    return ('User cancelled processing', False)
                interface.progress('Filtering {0} files'.format(lang),
                        self.operations_so_far.value / float(self.num_operations))
                input_path = self.paths[proj]
                out_path = (self.pb.getFilterOutputPath(proj, lang) +
                        os.path.basename(input_path) + '.' + self.suffixes[lang])
 
                (ok, gotsome) = the_filter.filterDiff(input_path, out_path)
                # this is actually tricky, if we got some output for java
                # in one project but not the other, then we know that
                # there can't be any clones
                self.got_some[lang] = self.got_some[lang] and gotsome
                if not ok:
                    return ('Error processing: ' + file_name, False)
                self.operations_so_far.incr()
            if self.paths['proj0'] == self.paths['proj1']:
                print "filterDiffFiles: two paths same, breaking!!"
                break


    def filterDiffs(self, interface):
        self.got_some = {'java':True, 'cxx':True, 'hxx':True}
#        self.haveJava = haveC = haveH = False
        self.pb = PathBuilder(self.tmpPath, force_clean = True)

        # First, filter the input diffs by file type, so that all c diffs
        # are in one set of files, and similarly for java/headers
        if self.processDirectory is True:
            self.filterDiffProjs(interface)
        else:
            self.filterDiffFiles(interface)


        # Second, change each diff into ccFinder input format
        converter = CCFXInputConverter()
        callback = lambda: interface.progress(
                'Converting to ccfx input format',
                self.operations_so_far.incr() / float(self.num_operations))
        converter.convert(self.pb, callback)

        #new and old for 3 langs
        self.num_operations = 3 * 2 
        self.operations_so_far = IntegerWrapper(0)
        

        clone_path = self.pb.getCCFXOutputPath()
        # Third, call ccfx for each directory
        worked = True
        for lang in ['java', 'cxx', 'hxx']:
            if not self.got_some[lang]:
                interface.progress('ccFinderX executing',
                                   self.operations_so_far.incr() / float(self.num_operations))
                continue
            old_path0 = self.pb.getCCFXInputPath(PathBuilder.PROJ0, lang, False)
            old_path1 = self.pb.getCCFXInputPath(PathBuilder.PROJ1, lang, False)
            new_path0 = self.pb.getCCFXInputPath(PathBuilder.PROJ0, lang, True)
            new_path1 = self.pb.getCCFXInputPath(PathBuilder.PROJ1, lang, True)
            tmp_old_out = clone_path + self.pb.getCCFXOutputFileName(
                    lang, is_new = False, is_tmp = True)
            tmp_new_out = clone_path + self.pb.getCCFXOutputFileName(
                    lang, is_new = True, is_tmp = True)
            old_out = clone_path + self.pb.getCCFXOutputFileName(
                    lang, is_new = False, is_tmp = False)
            new_out = clone_path + self.pb.getCCFXOutputFileName(
                    lang, is_new = True, is_tmp = False)
            
            if self.paths['proj0'] == self.paths['proj1']:
                old_path1 = old_path0
                new_path1 = new_path0   
                    
            worked = worked and self.ccfx.processPair(
                            old_path0, old_path1, tmp_old_out, old_out, lang)
            interface.progress('ccFinderX executing',
                self.operations_so_far.incr() / float(self.num_operations))
            worked = worked and self.ccfx.processPair(
                    new_path0, new_path1, tmp_new_out, new_out, lang)
            interface.progress('ccFinderX executing',
                self.operations_so_far.incr() / float(self.num_operations))
        if not worked:
            return ('ccFinderX execution failed', False)
       
         # Fourth, build up our database of clones 
        print "Repertoire filtering...."
        #new and old for 3 langs
        self.num_operations = 3 * 2 
        self.operations_so_far = IntegerWrapper(0)

        for lang in ['java', 'cxx', 'hxx']:
            if not self.got_some[lang]:
                interface.progress('Repertoire filtering based on operation',
                                   self.operations_so_far.incr() / float(self.num_operations))
                continue
            for is_new in [True, False]:
                output = convert_ccfx_output(self.pb, lang, is_new)
                rep_out_path = self.pb.getRepertoireOutputPath(lang, is_new)
                suffix = '_old.txt'
                if is_new:
                    suffix = '_new.txt'
                output.writeToFile(rep_out_path + lang + suffix)
                interface.progress('Repertoire filtering based on operation',
                                   self.operations_so_far.incr() / float(self.num_operations))
                

        print "Processing successful!!"
        return ('Processing successful', True)