xaizek / uncov (License: AGPLv3+) (since 2018-12-07)
Uncov(er) is a tool that collects and processes code coverage reports.
<root> / src / BuildHistory.cpp (5cf008685a31ce720642c7e2e798de752c9bfb2f) (12KiB) (mode 100644) [raw]
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 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
// Copyright (C) 2016 xaizek <xaizek@posteo.net>
//
// This file is part of uncov.
//
// uncov is free software: you can redistribute it and/or modify
// it under the terms of version 3 of the GNU Affero General Public License as
// published by the Free Software Foundation.
//
// uncov is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with uncov.  If not, see <http://www.gnu.org/licenses/>.

#include "BuildHistory.hpp"

#include <boost/optional.hpp>

#include <algorithm>
#include <iterator>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include <map>

#include "utils/md5.hpp"
#include "DB.hpp"

static std::string hashCoverage(const std::vector<int> &vec);
static void updateDBSchema(DB &db, int fromVersion);

//! Current database scheme version.
const int AppDBVersion = 2;

File::File(std::string path, std::string hash, std::vector<int> coverage)
    : path(std::move(path)), hash(std::move(hash)),
      coverage(std::move(coverage))
{
    coveredCount = 0;
    missedCount = 0;
    for (int hits : this->coverage) {
        if (hits == 0) {
            ++missedCount;
        } else if (hits > 0) {
            ++coveredCount;
        }
    }
}

const std::string &
File::getPath() const
{
    return path;
}

const std::string &
File::getHash() const
{
    return hash;
}

const std::vector<int> &
File::getCoverage() const
{
    return coverage;
}

int
File::getCoveredCount() const
{
    return coveredCount;
}

int
File::getMissedCount() const
{
    return missedCount;
}

BuildData::BuildData(std::string ref, std::string refName)
    : ref(std::move(ref)), refName(std::move(refName))
{
}

void
BuildData::addFile(File file)
{
    files.emplace(file.getPath(), std::move(file));
}

int
operator<<(DB &db, const BuildData &bd)
{
    int coveredCount = 0;
    int missedCount = 0;
    for (auto entry : bd.files) {
        File &file = entry.second;
        coveredCount += file.getCoveredCount();
        missedCount += file.getMissedCount();
    }

    Transaction transaction = db.makeTransaction();

    db.execute("INSERT INTO builds (vcsref, vcsrefname, covered, missed) "
               "VALUES (:ref, :refname, :covered, :missed)",
               { ":ref"_b = bd.ref,
                 ":refname"_b = bd.refName,
                 ":covered"_b = coveredCount,
                 ":missed"_b = missedCount });

    const int buildid = db.getLastRowId();

    for (auto entry : bd.files) {
        File &file = entry.second;

        const std::vector<int> &coverage = file.getCoverage();
        const std::string covHash = hashCoverage(coverage);

        int fileid = -1;

        for (std::tuple<int> val :
            db.queryAll("SELECT fileid FROM files "
                        "WHERE path = :path AND hash = :hash AND "
                              "covhash = :covhash",
                        { ":path"_b = file.getPath(),
                          ":hash"_b = file.getHash(),
                          ":covhash"_b = covHash })) {
            fileid = std::get<0>(val);
        }

        if (fileid == -1) {
            db.execute("INSERT INTO files (path, hash, covhash, coverage) "
                       "VALUES (:path, :hash, :covhash, :coverage)",
                       { ":path"_b = file.getPath(),
                         ":hash"_b = file.getHash(),
                         ":covhash"_b = covHash,
                         ":coverage"_b = coverage });
            fileid = db.getLastRowId();
        }

        db.execute("INSERT INTO filemap (buildid, fileid) "
                   "VALUES (:buildid, :fileid)",
                   { ":buildid"_b = buildid,
                     ":fileid"_b = fileid });
    }

    transaction.commit();

    return buildid;
}

/**
 * @brief Hashes coverage vector into a string.
 *
 * @param vec Coverage to hash.
 *
 * @returns String containing MD5 hash of the coverage.
 */
static std::string
hashCoverage(const std::vector<int> &vec)
{
    std::ostringstream oss;
    std::copy(vec.cbegin(), vec.cend(), std::ostream_iterator<int>(oss, " "));
    return md5(oss.str());
}

Build::Build(int id, std::string ref, std::string refName,
             int coveredCount, int missedCount, int timestamp,
             DataLoader &loader)
    : id(id), ref(std::move(ref)), refName(std::move(refName)),
      coveredCount(coveredCount), missedCount(missedCount),
      timestamp(timestamp), loader(&loader)
{
}

int
Build::getId() const
{
    return id;
}

const std::string &
Build::getRef() const
{
    return ref;
}

const std::string &
Build::getRefName() const
{
    return refName;
}

std::time_t
Build::getTimestamp() const
{
    return timestamp;
}

int
Build::getCoveredCount() const
{
    return coveredCount;
}

int
Build::getMissedCount() const
{
    return missedCount;
}

std::vector<std::string>
Build::getPaths() const
{
    // Make sure file path to file id mapping is loaded.
    if (pathMap.empty()) {
        pathMap = loader->loadPaths(id);
    }

    std::vector<std::string> paths;
    paths.reserve(pathMap.size());
    for (const auto &entry : pathMap) {
        paths.push_back(entry.first);
    }
    return paths;
}

boost::optional<File &>
Build::getFile(const std::string &path) const
{
    // Check if this file was already loaded.
    const auto fileMatch = files.find(path);
    if (fileMatch != files.end()) {
        return fileMatch->second;
    }

    // Make sure file path to file id mapping is loaded.
    if (pathMap.empty()) {
        pathMap = loader->loadPaths(id);
    }

    // Requested file should be in the map.
    const auto pathMatch = pathMap.find(path);
    if (pathMatch == pathMap.end()) {
        return {};
    }

    // Load the file and cache it.
    if (boost::optional<File> file = loader->loadFile(pathMatch->second)) {
        return files.emplace(path, std::move(*file)).first->second;
    }

    return {};
}

BuildHistory::BuildHistory(DB &db) : db(db)
{
    std::tuple<int> vals = db.queryOne("pragma user_version");

    const int fileDBVersion = std::get<0>(vals);
    if (fileDBVersion > AppDBVersion) {
        throw std::runtime_error("Database schema version is newer than "
                                 "supported by the application (up to " +
                                 std::to_string(AppDBVersion) + "): " +
                                 std::to_string(fileDBVersion));
    }

    if (fileDBVersion < AppDBVersion) {
        updateDBSchema(db, fileDBVersion);
    }
}

/**
 * @brief Performs update of database scheme to the latest version.
 *
 * This process might take some time.  Should either succeed or be no-op.
 *
 * @param db Database to update.
 * @param fromVersion Current version of scheme.
 */
static void
updateDBSchema(DB &db, int fromVersion)
{
    Transaction transaction = db.makeTransaction();

    switch (fromVersion) {
        case 0:
            db.execute(R"(
                CREATE TABLE builds (
                    buildid INTEGER,
                    vcsref TEXT NOT NULL,
                    vcsrefname TEXT NOT NULL,
                    covered INTEGER NOT NULL,
                    missed INTEGER NOT NULL,
                    timestamp INTEGER NOT NULL
                              DEFAULT (CAST(strftime('%s', 'now') AS INT)),

                    PRIMARY KEY (buildid)
                )
            )");
            db.execute(R"(
                CREATE TABLE files (
                    fileid INTEGER,
                    path TEXT NOT NULL,
                    hash TEXT NOT NULL,
                    covhash TEXT NOT NULL,
                    coverage BLOB NOT NULL,

                    PRIMARY KEY (fileid)
                )
            )");
            db.execute(R"(
                CREATE TABLE filemap (
                    buildid INTEGER,
                    fileid INTEGER,

                    FOREIGN KEY (buildid) REFERENCES builds(buildid),
                    FOREIGN KEY (fileid) REFERENCES files(fileid)
                )
            )");
            // Fall through.
        case 1:
            db.execute(R"(
                CREATE INDEX files_idx ON files(path, hash, covhash)
            )");
            // Fall through.
        case AppDBVersion:
            break;
    }

    db.execute("pragma user_version = " + std::to_string(AppDBVersion));
    transaction.commit();

    // Compact database after migration by defragmenting it.
    db.execute("VACUUM");
}

Build
BuildHistory::addBuild(const BuildData &buildData)
{
    const int buildid = (db << buildData);
    return *getBuild(buildid);
}

int
BuildHistory::getLastBuildId()
{
    try {
        std::tuple<int> vals = db.queryOne("SELECT buildid FROM builds "
                                           "ORDER BY buildid DESC LIMIT 1");
        return std::get<0>(vals);
    } catch (const std::runtime_error &) {
        return 0;
    }
}

int
BuildHistory::getNToLastBuildId(int n)
{
    try {
        std::tuple<int> vals = db.queryOne("SELECT buildid FROM builds "
                                           "ORDER BY buildid DESC "
                                           "LIMIT 1 OFFSET :n",
                                           { ":n"_b = n } );
        return std::get<0>(vals);
    } catch (const std::runtime_error &) {
        return 0;
    }
}

int
BuildHistory::getPreviousBuildId(int id)
{
    // TODO: try looking for closest build in terms of commits.
    return id - 1;
}

boost::optional<Build>
BuildHistory::getBuild(int id)
{
    try {
        DataLoader &loader = *this;
        std::tuple<std::string, std::string, int, int, int> vals =
            db.queryOne("SELECT vcsref, vcsrefname, covered, missed, timestamp "
                        "FROM builds WHERE buildid = :buildid",
                        { ":buildid"_b = id } );
        return Build(id, std::get<0>(vals), std::get<1>(vals),
                     std::get<2>(vals), std::get<3>(vals), std::get<4>(vals),
                     loader);
    } catch (const std::runtime_error &) {
        return {};
    }
}

/**
 * @brief Turns table rows into vector of builds.
 *
 * @tparam T Type of range of rows.
 *
 * @param range  Table rows (DB::Rows).
 * @param loader Reference to loader of file and path data.
 *
 * @returns The list.
 */
template <typename T>
std::vector<Build>
listBuilds(T &&rows, DataLoader &loader)
{
    std::vector<Build> builds;
    for (std::tuple<int, std::string, std::string, int, int, int> vals : rows) {
        builds.emplace_back(std::get<0>(vals), std::get<1>(vals),
                            std::get<2>(vals), std::get<3>(vals),
                            std::get<4>(vals), std::get<5>(vals), loader);
    }
    return builds;
}

std::vector<Build>
BuildHistory::getBuilds()
{
    return listBuilds(db.queryAll("SELECT buildid, vcsref, vcsrefname, "
                                         "covered, missed, timestamp "
                                  "FROM builds"),
                      *this);
}

std::vector<Build>
BuildHistory::getBuildsOn(const std::string &refName)
{
    return listBuilds(db.queryAll("SELECT buildid, vcsref, vcsrefname, "
                                         "covered, missed, timestamp "
                                  "FROM builds "
                                  "WHERE vcsrefname = :refname",
                                  { ":refname"_b = refName }),
                      *this);
}

std::map<std::string, int>
BuildHistory::loadPaths(int buildid)
{
    std::map<std::string, int> paths;
    for (std::tuple<std::string, int> vals : db.queryAll(
            "SELECT path, fileid FROM files NATURAL JOIN filemap "
            "WHERE buildid = :buildid",
            { ":buildid"_b = buildid })) {
        paths.emplace(std::move(std::get<0>(vals)), std::get<1>(vals));
    }
    return paths;
}

boost::optional<File>
BuildHistory::loadFile(int fileid)
{
    try {
        std::tuple<std::string, std::string, std::vector<int>> vals =
            db.queryOne("SELECT path, hash, coverage FROM files "
                        "WHERE fileid = :fileid",
                        { ":fileid"_b = fileid });

        return File(std::move(std::get<0>(vals)), std::move(std::get<1>(vals)),
                    std::move(std::get<2>(vals)));
    } catch (const std::runtime_error &) {
        return {};
    }
}
Hints

Before first commit, do not forget to setup your git environment:
git config --global user.name "your_name_here"
git config --global user.email "your@email_here"

Clone this repository using HTTP(S):
git clone https://code.reversed.top/user/xaizek/uncov

Clone this repository using ssh (do not forget to upload a key first):
git clone ssh://rocketgit@code.reversed.top/user/xaizek/uncov

You are allowed to anonymously push to this repository.
This means that your pushed commits will automatically be transformed into a pull request:
... clone the repository ...
... make some changes and some commits ...
git push origin master