<commit_before>#!/usr/local/bin/python2.7
"""
    Copyright (c) 2015 <NAME>

    part of OPNsense (https://www.opnsense.org/)

    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.

    --------------------------------------------------------------------------------------
    Generate dependency maps for legacy files.
    To use this script, please install graphviz package ( pkg install graphviz )
"""
import time
import os
import os.path

# set source and target directories
target_directory = '/tmp/legacy/'
src_root = '/usr/local/'


class DependancyCrawler(object):
    """ Legacy dependancy crawler and grapher
    """
    def __init__(self):
        self._all_dependancies = {}

    def fetch_php(self, src_filename):
        # create a new list for this base filename
        # to avoid too much complexity, we will assume that filenames are unique.
        base_filename = os.path.basename(src_filename)
        self._all_dependancies[base_filename] = []

        source_data = open(src_filename).read()
        # fetch all include, include_once, require, require_once statements and
        # add dependancies to object dependancy list.
        for tag in ('include', 'require'):
            data = source_data
            while True:
                startpos = data.find(tag)
                if startpos == -1:
                    break
                else:
                    strlen = data[startpos:].find(';')
                    if strlen > -1:
                        # parse (single) statement, check if this could be an include type command
                        dep_stmt = data[startpos-1:strlen+startpos]
                        if dep_stmt[0] in (' ', '\n'):
                            dep_stmt = dep_stmt[1:].replace("'", '"')
                            if dep_stmt.find('\n') == -1 and dep_stmt.count('"') == 2:
                                dep_filename = dep_stmt.split('"')[1]
                                if dep_filename not in self._all_dependancies[base_filename]:
                                    self._all_dependancies[base_filename].append(dep_filename)
                        data = data[strlen+startpos:]

    def crawl(self, root, analyse_dirs=('www', 'etc', 'captiveportal', 'sbin')):
        """ Crawl through legacy code
        :param root: start crawling at
        :param analyse_dirs: only analyse these directories
        :return: None
        """
        for analyse_dir in analyse_dirs:
            analyse_dir = ('%s/%s' % (root, analyse_dir)).replace('//', '/')
            for wroot, wdirs, wfiles in os.walk(analyse_dir):
                for src_filename in wfiles:
                    src_filename = '%s/%s' % (wroot, src_filename)
                    if src_filename.split('.')[-1] in ('php', 'inc') \
                            or open(src_filename).read(1024).find('/bin/php') > -1:
                        self.fetch_php(src_filename)

    def get_total_files(self):
        """ get total number of analysed files
        :return: int
        """
        return len(self._all_dependancies)

    def get_total_dependancies(self):
        """ get total number of dependencies
        :return: int
        """
        count = 0
        for src_filename in self._all_dependancies:
            count += len(self._all_dependancies[src_filename])
        return count<commit_msg>(dev) add .class to crawler<commit_after>#!/usr/local/bin/python2.7
"""
    Copyright (c) 2015 <NAME>

    part of OPNsense (https://www.opnsense.org/)

    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.

    --------------------------------------------------------------------------------------
    Generate dependency maps for legacy files.
    To use this script, please install graphviz package ( pkg install graphviz )
"""
import time
import os
import os.path

# set source and target directories
target_directory = '/tmp/legacy/'
src_root = '/usr/local/'


class DependancyCrawler(object):
    """ Legacy dependancy crawler and grapher
    """
    def __init__(self):
        self._all_dependancies = {}

    def fetch_php(self, src_filename):
        # create a new list for this base filename
        # to avoid too much complexity, we will assume that filenames are unique.
        base_filename = os.path.basename(src_filename)
        self._all_dependancies[base_filename] = []

        source_data = open(src_filename).read()
        # fetch all include, include_once, require, require_once statements and
        # add dependancies to object dependancy list.
        for tag in ('include', 'require'):
            data = source_data
            while True:
                startpos = data.find(tag)
                if startpos == -1:
                    break
                else:
                    strlen = data[startpos:].find(';')
                    if strlen > -1:
                        # parse (single) statement, check if this could be an include type command
                        dep_stmt = data[startpos-1:strlen+startpos]
                        if dep_stmt[0] in (' ', '\n'):
                            dep_stmt = dep_stmt[1:].replace("'", '"')
                            if dep_stmt.find('\n') == -1 and dep_stmt.count('"') == 2:
                                dep_filename = dep_stmt.split('"')[1]
                                if dep_filename not in self._all_dependancies[base_filename]:
                                    self._all_dependancies[base_filename].append(dep_filename)
                        data = data[strlen+startpos:]

    def crawl(self, root, analyse_dirs=('www', 'etc', 'captiveportal', 'sbin')):
        """ Crawl through legacy code
        :param root: start crawling at
        :param analyse_dirs: only analyse these directories
        :return: None
        """
        for analyse_dir in analyse_dirs:
            analyse_dir = ('%s/%s' % (root, analyse_dir)).replace('//', '/')
            for wroot, wdirs, wfiles in os.walk(analyse_dir):
                for src_filename in wfiles:
                    src_filename = '%s/%s' % (wroot, src_filename)
                    if src_filename.split('.')[-1] in ('php', 'inc','class') \
                            or open(src_filename).read(1024).find('/bin/php') > -1:
                        self.fetch_php(src_filename)

    def get_total_files(self):
        """ get total number of analysed files
        :return: int
        """
        return len(self._all_dependancies)

    def get_total_dependancies(self):
        """ get total number of dependencies
        :return: int
        """
        count = 0
        for src_filename in self._all_dependancies:
            count += len(self._all_dependancies[src_filename])
        return count
{'fraction_non_alphanumeric': 0.10332749562171628, 'fraction_numerical': 0.005035026269702277, 'mean_word_length': 2.0722932078009415, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 9, 'https://': 2, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4029031', 'n_tokens_mistral': 2442, 'n_tokens_neox': 2269, 'n_words': 833}