aboutsummaryrefslogtreecommitdiffstats
path: root/3rdparty/python-console/ParseHelper.BracketParseState.cpp
blob: 4ce41737ebaa412ccd61348e250667025dd83bb5 (plain)
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
/**
Copyright (c) 2014 Alex Tsui

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "ParseHelper.h"
#include <string>
#include <sstream>

const std::string ParseHelper::BracketParseState::OpeningBrackets = "[({";
const std::string ParseHelper::BracketParseState::ClosingBrackets = "])}";

bool ParseHelper::BracketParseState::HasOpenBrackets(const std::string& str)
{
    std::list<char> brackets;
    bool hasOpenBrackets = LoadBrackets(str, &brackets);
    return hasOpenBrackets;
}

bool ParseHelper::BracketParseState::LoadBrackets(const std::string& str,
    std::list<char>* stack)
{
    if ( !stack )
        return false;

    stack->clear();
    for (size_t i = 0; i < str.size(); ++i)
    {
        if (OpeningBrackets.find_first_of(str[i]) != std::string::npos)
        {
            stack->push_back(str[i]);
        }
        else
        {
            size_t t = ClosingBrackets.find_first_of(str[i]);
            if (t != std::string::npos)
            {
                if (t != OpeningBrackets.find_first_of(stack->back()))
                    return false;
                stack->pop_back();
            }
        }
    }
    return stack->size();
}

ParseHelper::BracketParseState::BracketParseState( ParseHelper& parent, const std::string& firstLine ):
    ParseState( parent )
{
    /*bool hasOpenBrackets = */ LoadBrackets( firstLine, &brackets );
    //assert( hasOpenBrackets );
    m_buffer.push_back( firstLine );
}

bool ParseHelper::BracketParseState::process(const std::string& str)
{
    // update brackets stack
    for (size_t i = 0; i < str.size(); ++i)
    {
        if (OpeningBrackets.find_first_of(str[i]) != std::string::npos)
        {
            brackets.push_back(str[i]);
        }
        else
        {
            size_t t = ClosingBrackets.find_first_of(str[i]);
            if (t != std::string::npos)
            {
                // reset state if unmatched brackets seen
                if (t != OpeningBrackets.find_first_of(brackets.back()))
                {
                    parent.reset( );
                    ParseMessage msg(1, "Invalid syntax");
                    parent.broadcast( msg );
                    return true;
                }
                brackets.pop_back();
            }
        }
    }

    // if we've cleared the stack, we've finished accepting input here
    if (!brackets.size())
    {
        // squash buffered lines and place it on parent::commandBuffer
        std::stringstream ss;
        for (std::list<std::string>::const_iterator it = m_buffer.begin();
            it != m_buffer.end(); ++it )
        {
            ss << *it << "\n";
        }
        ss << str;
        parent.commandBuffer.push_back(ss.str());
        parent.stateStack.pop_back( );
        return false;
    }
    else
    {
        // buffer and expect more lines
        m_buffer.push_back( str );
        return true;
    }
}
="p">(st.st_mtime) << 64 return (progname, progversion) extensions = ( ".tar.gz", ".tar.bz2", ".orig.tar.gz", ".orig.tar.bz2", ".zip", ".tgz", ".tbz", ) versionRegex = ( (re.compile(r"(.+)[-_]([0-9a-fA-F]{40,40})"), parseVer_GIT), # xxx-GIT_SHASUM (re.compile(r"(.+)[-_](\d+)\.(\d+)\.(\d+)\.(\d+)"), parseVer_1234), # xxx-1.2.3.4 (re.compile(r"(.+)[-_](\d\d\d\d)-?(\d\d)-?(\d\d)"), parseVer_ymd), # xxx-YYYY-MM-DD (re.compile(r"(.+)[-_](\d+)\.(\d+)\.(\d+)(\w?)"), parseVer_123), # xxx-1.2.3a (re.compile(r"(.+)[-_](\d+)_(\d+)_(\d+)"), parseVer_123), # xxx-1_2_3 (re.compile(r"(.+)[-_](\d+)\.(\d+)(\w?)"), parseVer_12), # xxx-1.2a (re.compile(r"(.+)[-_]r?(\d+)"), parseVer_r), # xxx-r1111 ) blacklist = [ ("linux", re.compile(r"linux-.*")), ("gcc", re.compile(r"gcc-.*")), ("wl_apsta", re.compile(r"wl_apsta.*")), (".fw", re.compile(r".*\.fw")), (".arm", re.compile(r".*\.arm")), (".bin", re.compile(r".*\.bin")), ("rt-firmware", re.compile(r"RT[\d\w]+_Firmware.*")), ] class EntryParseError(Exception): pass class Entry: def __init__(self, directory, filename): self.directory = directory self.filename = filename self.progname = "" self.fileext = "" for ext in extensions: if filename.endswith(ext): filename = filename[0:0-len(ext)] self.fileext = ext break else: print self.filename, "has an unknown file-extension" raise EntryParseError("ext") for (regex, parseVersion) in versionRegex: match = regex.match(filename) if match: (self.progname, self.version) = parseVersion( match, directory + "/" + filename + self.fileext) break else: print self.filename, "has an unknown version pattern" raise EntryParseError("ver") def deleteFile(self): path = (self.directory + "/" + self.filename).replace("//", "/") print "Deleting", path if not opt_dryrun: os.unlink(path) def __eq__(self, y): return self.filename == y.filename def __ge__(self, y): return self.version >= y.version def usage(): print "OpenWRT download directory cleanup utility" print "Usage: " + sys.argv[0] + " [OPTIONS] <path/to/dl>" print "" print " -d|--dry-run Do a dry-run. Don't delete any files" print " -B|--show-blacklist Show the blacklist and exit" print " -w|--whitelist ITEM Remove ITEM from blacklist" def main(argv): global opt_dryrun try: (opts, args) = getopt.getopt(argv[1:], "hdBw:", [ "help", "dry-run", "show-blacklist", "whitelist=", ]) if len(args) != 1: usage() return 1 except getopt.GetoptError: usage() return 1 directory = args[0] for (o, v) in opts: if o in ("-h", "--help"): usage() return 0 if o in ("-d", "--dry-run"): opt_dryrun = True if o in ("-w", "--whitelist"): for i in range(0, len(blacklist)): (name, regex) = blacklist[i] if name == v: del blacklist[i] break else: print "Whitelist error: Item", v,\ "is not in blacklist" return 1 if o in ("-B", "--show-blacklist"): for (name, regex) in blacklist: print name return 0 # Create a directory listing and parse the file names. entries = [] for filename in os.listdir(directory): if filename == "." or filename == "..": continue for (name, regex) in blacklist: if regex.match(filename): if opt_dryrun: print filename, "is blacklisted" break else: try: entries.append(Entry(directory, filename)) except (EntryParseError), e: pass # Create a map of programs progmap = {} for entry in entries: if entry.progname in progmap.keys(): progmap[entry.progname].append(entry) else: progmap[entry.progname] = [entry,] # Traverse the program map and delete everything but the last version for prog in progmap: lastVersion = None versions = progmap[prog] for version in versions: if lastVersion is None or version >= lastVersion: lastVersion = version if lastVersion: for version in versions: if version != lastVersion: version.deleteFile() if opt_dryrun: print "Keeping", lastVersion.filename return 0 if __name__ == "__main__": sys.exit(main(sys.argv))