cmdline.cpp 22.6 KB
Newer Older
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
/* This file is part of the Chakra project

   Copyright (C) 2011 Lisa "shainer" Vitolo <shainer@chakra-project.org>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.
*/

#include "cmdline.h"

#include <kaboutdata.h>
#include <klocalizedstring.h>
#include <QDebug>

/*
 * Build our database of accepted operations and options with the right properties and associations
 */
CmdLine::CmdLine()
: parsed(false)
{
    typechars.insert("D", APM::DatabaseOperationType);
    typechars.insert("Q", APM::QueryOperationType);
    typechars.insert("R", APM::RemoveOperationType);
    typechars.insert("S", APM::SyncOperationType);
    typechars.insert("U", APM::UpgradeOperationType);
    
    /*
     * The argument list is only meaningful after reading the command line, so for now it stays empty
     */
    AkabeiOption querypkgfile(APM::QueryPackageFile, "p", "file", "Queries a package file instead of the database", true);
    AkabeiOption showlocal(APM::ShowLocal, "m", "foreign", "Shows packages which were not found in the Sync-db(s)", false);
    AkabeiOption showless(APM::ShowLess, "q", "quiet", "Shows less information in queries and searches", false);
    AkabeiOption installasdeps(APM::InstallAsDeps, "", "asdeps", "Install all packages as non-explicit", false);
    AkabeiOption installasexplicit(APM::InstallAsExplicit, "", "asexplicit", "APM::Install all packages as explicit", false);
    AkabeiOption skipdependencycheck(APM::SkipDependencyCheck, "w", "nodeps", "Skip dependency check", false);
    AkabeiOption force(APM::Force, "f", "force", "Force installation. Overwrite file conflicts", false);
    AkabeiOption downloadonly(APM::DownloadOnly, "d", "downloadonly", "Downloads packages without installing or upgrading them", false);
    AkabeiOption onlyneeded(APM::OnlyNeeded, "", "needed", "Up-to-date packages are not reinstalled", false);
    AkabeiOption ignore(APM::Ignore, "", "ignore", "Ignores a certain package. Can be used more than once.", true);
    AkabeiOption ignoregroup(APM::IgnoreGroup, "", "ignoregroup", "Ignores upgrade of a group", true);
    AkabeiOption databaseonly(APM::DatabaseOnly, "k", "dbonly", "Only remove database entries", false);
44
    AkabeiOption removeconfig(APM::RemoveConfig, "n", "save", "Also remove configuration files", false);
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
    AkabeiOption recursive(APM::Recursive, "s", "recursive", "Remove dependencies as well. (-ss includes explicitely installed dependencies)", false);
    AkabeiOption rootdir(APM::RootDir, "", "root", "Set a different root dir", true);
    AkabeiOption cachedir(APM::CacheDir, "", "cachedir", "Set a different cache dir", true);
    AkabeiOption dbpath(APM::DBPath, "b", "dbpath", "Set a different database dir", false);
    
    acceptedOptions << querypkgfile << showlocal << showless << installasdeps << installasexplicit << skipdependencycheck;
    acceptedOptions << force << downloadonly << onlyneeded << ignore << ignoregroup << databaseonly << removeconfig << recursive;
    acceptedOptions << rootdir << cachedir << dbpath;
    
    AkabeiOperation database(APM::DatabaseOperationType, APM::DatabaseOperation, "D", "", "", false);
    
    AkabeiOperation changelog(APM::QueryOperationType, APM::ShowChangelog, "c", "changelog", "Shows changelog of the package", true);
    changelog.addOption(querypkgfile);
    
    AkabeiOperation installedasdeps(APM::QueryOperationType, APM::ShowInstalledAsDeps, "d", "deps", "Shows packages which got installed as dependencies", false);
    installedasdeps.addOption(querypkgfile);
    installedasdeps.addOption(ignore);
    installedasdeps.addOption(ignoregroup);
    
    AkabeiOperation installedexp(APM::QueryOperationType, APM::ShowInstalledExplicitely, "e", "explicit", "Shows packages which got installed explicitely", false);
    installedexp.addOption(querypkgfile);
    installedexp.addOption(ignore);
    installedexp.addOption(ignoregroup);
    
    AkabeiOperation checkfiles(APM::QueryOperationType, APM::CheckFiles, "k", "check", "Check if the files of the package are available", true);
    checkfiles.addOption(querypkgfile);
    checkfiles.addOption(showlocal);
    
    AkabeiOperation showowner(APM::QueryOperationType, APM::ShowOwner, "o", "owns", "Returns the package which contains the file", true);
    showowner.addOption(querypkgfile);
    showowner.addOption(showlocal);
    
    AkabeiOperation notrequired(APM::QueryOperationType, APM::ShowNotRequired, "t", "unrequired", "Returns packages which are not required by others", false);
    notrequired.addOption(querypkgfile);
    notrequired.addOption(ignore);
    notrequired.addOption(ignoregroup);
    
    AkabeiOperation upgradeable(APM::QueryOperationType, APM::ShowUpgradeable, "u", "upgrades", "Returns upgradeable packages", false);
    upgradeable.addOption(querypkgfile);
    upgradeable.addOption(ignore);
    upgradeable.addOption(ignoregroup);
    
    AkabeiOperation groupsl(APM::QueryOperationType, APM::ShowPackagesOfGroupLocal, "g", "groups", "Shows all packages in a package group", true);
    groupsl.addOption(ignore);
    
    AkabeiOperation infol(APM::QueryOperationType, APM::ShowInformationLocal, "i", "info", "Shows package information", true);
    infol.addOption(showless);
    
    AkabeiOperation searchl(APM::QueryOperationType, APM::SearchLocal, "s", "search", "Searches repositories for a word", true);
    searchl.addOption(ignore);
    searchl.addOption(ignoregroup);
    
    AkabeiOperation remove(APM::RemoveOperationType, APM::Remove, "R", "remove", "Remove packages", true);
    remove.addOption(skipdependencycheck);
    remove.addOption(force);
    remove.addOption(databaseonly);
    remove.addOption(removeconfig);
    remove.addOption(recursive);
    
    AkabeiOperation cascade(APM::RemoveOperationType, APM::Cascade, "c", "cascade", "Remove packages with their dependencies", true);
    
    AkabeiOperation unneeded(APM::RemoveOperationType, APM::Unneeded, "u", "unneeded", "Remove not needed packages", false);
    unneeded.addOption(ignore);
    unneeded.addOption(ignoregroup);
    
    AkabeiOperation install(APM::SyncOperationType, APM::Install, "S", "install", "Install packages", true);
    install.addOption(installasdeps);
    install.addOption(installasexplicit);
    install.addOption(skipdependencycheck);
    install.addOption(force);
    install.addOption(downloadonly);
    install.addOption(onlyneeded);

    AkabeiOperation removeold(APM::SyncOperationType, APM::RemoveOldFromCache, "c", "clean", "Remove old packages from cache", false);
    
    AkabeiOperation removeallcache(APM::SyncOperationType, APM::RemoveAllCache, "cc", "", "Remove all packages from cache", false);
    
    AkabeiOperation groups(APM::SyncOperationType, APM::ShowPackagesOfGroup, "g", "groups", "Shows all packages in a package group", true);
    groups.addOption(ignore);
    
    AkabeiOperation info(APM::SyncOperationType, APM::ShowInformation, "i", "info", "Shows package information", true);
    info.addOption(showless);
    
    AkabeiOperation search(APM::SyncOperationType, APM::Search, "s", "search", "Searches repositories for a word", true);
    search.addOption(ignore);
    search.addOption(ignoregroup);
    
    AkabeiOperation listrepo(APM::SyncOperationType, APM::ListRepo, "l", "list", "List all packages in a repository", true);
    listrepo.addOption(querypkgfile);
    listrepo.addOption(showlocal);
    listrepo.addOption(ignore);
    listrepo.addOption(ignoregroup);
    
    AkabeiOperation updatedb(APM::SyncOperationType, APM::UpdateDatabases, "y", "refresh", "Refresh database", false);
    
    AkabeiOperation updatesys(APM::SyncOperationType, APM::UpdateSystem, "u", "sysupgrade", "Update system", false);
    updatesys.addOption(downloadonly);
    updatesys.addOption(ignore);
    updatesys.addOption(ignoregroup);
    
    AkabeiOperation updatedbandsys(APM::SyncOperationType, APM::UpdateDatabaseAndSystem, "", "", "Refresh database and update system", false);
    updatedbandsys.addOption(downloadonly);
    updatedbandsys.addOption(ignore);
    updatedbandsys.addOption(ignoregroup);
    
    AkabeiOperation upgrade(APM::UpgradeOperationType, APM::Upgrade, "U", "", "Upgrade operation", true);
    upgrade.addOption(downloadonly);
    upgrade.addOption(ignore);
    upgrade.addOption(ignoregroup);
    
    AkabeiOperation help(APM::NoType, APM::Help, "h", "help", "Shows the help message", false);
    
    AkabeiOperation version(APM::NoType, APM::Version, "v", "version", "Shows Akabei version", false);
    
    AkabeiOperationList tmp2;
    tmp2 << removeallcache << install << remove << database << changelog << installedasdeps << installedexp;
    tmp2 << checkfiles << showowner << notrequired << upgradeable << cascade;
    tmp2 << removeold << groups << info << listrepo << groupsl << searchl << infol;
    tmp2 << search << updatedb << updatesys << updatedbandsys << upgrade << help << version;
    
    foreach (AkabeiOperation op, tmp2) {
        /* These options are associated to every operation */
        op.addOption(rootdir);
        op.addOption(cachedir);
        op.addOption(dbpath);
        
        /*
         * This hash associating command (often the short one) and operation is useful later because
         * one command can be associated to more operations and even options
         */
175 176 177 178 179 180 181
        if (!op.commandShort.isEmpty()) {
            acceptedOperations.insertMulti(op.commandShort, op);
        }
        if (!op.commandLong.isEmpty()) {
            acceptedOperations.insertMulti(op.commandLong, op);
        }
        
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
    }
}

AkabeiOption::AkabeiOption(APM::OptionName n, const char *cs, const char *cl, const char *desc, bool hasArg)
{
    QStringList unused;
    init(n, cs, cl, desc, hasArg, unused);
}

AkabeiOption::AkabeiOption(APM::OptionName n, const char *cs, const char *cl, const char *desc, bool hasArg, QStringList a)
{
    init(n, cs, cl, desc, hasArg, a);
}

void AkabeiOption::init(APM::OptionName n, const char *cs, const char *cl, const char *desc, bool hasArg, QStringList a)
{
    name = n;
    commandShort = QString::fromAscii(cs).toUtf8();
    commandLong = QString::fromAscii(cl).toUtf8();
    description = ki18n(desc);
    this->hasArg = hasArg;
    this->args = a;
}

AkabeiOperation::AkabeiOperation(APM::OperationType t, APM::OperationName n, const char *cs, const char *cl, const char *desc, bool hasFreeArgs)
{
    QStringList args;
    init(t, n, cs, cl, desc, hasFreeArgs, args);
}

AkabeiOperation::AkabeiOperation(APM::OperationType t, APM::OperationName n, const char *cs, const char *cl, const char *desc, bool hasFreeArgs, QStringList args)
{
    init(t, n, cs, cl, desc, hasFreeArgs, args);
}

AkabeiOperation::AkabeiOperation()
{
    init(APM::NoType, APM::None, "", "", "", false, QStringList());
}

/*
 * This requires some explanation (and maybe some polishing)
 * 
 * 0: APM::None means no operation has still been set, so no problem here.
 * 1: -S is Install, but for example -Ss is Search. Same for most removing operations. This overlapping is fine.
 * 2: the elements in a hash aren't sorted, so "s" may be found before "S".
 * 3: for -Scc, both "cc" and "c" are found. Only the first one is good.
 * 4: -Sy is UpdateDatabases, -Su is UpdateSystem, but -Syu is APM::UpdateDatabaseAndSystem (only linked operations accepted).
 * 5: All the rest is invalid
 */
void AkabeiOperation::set(AkabeiOperation& other)
{
    if ((this->type == APM::SyncOperationType && other.name == APM::Install) || (this->type == APM::RemoveOperationType && other.name == APM::Remove) || (this->name == APM::RemoveAllCache && other.commandShort == "c")) {
        return;
    }
    
238 239 240 241 242
    /* This is because sometimes the same operation is checked twice (also due to the hash) */
    if (this->name == other.name) {
        return;
    }
    
243 244 245 246
    if (this->name == APM::None || this->name == APM::Remove || this->name == APM::Install) {
        this->name = other.name;
        this->type = other.type;
        this->options = other.options;
247 248
        this->commandLong = other.commandLong;
        this->commandShort = other.commandShort;
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
        this->hasFreeArgs = other.hasFreeArgs;
    } else if ((this->name == APM::UpdateDatabases && other.name == APM::UpdateSystem) || (this->name == APM::UpdateSystem && other.name == APM::UpdateDatabases)) {
        this->name = APM::UpdateDatabaseAndSystem;
        this->type = APM::SyncOperationType;
        this->hasFreeArgs = false;
    } else {
        throw CmdLineException("Multiple operations present.");
    }
}

void AkabeiOperation::init(APM::OperationType t, APM::OperationName n, const char *cs, const char *cl, const char *desc, bool hasFreeArgs, QStringList args)
{
    type = t;
    name = n;
    commandShort = QString::fromAscii(cs).toUtf8();
    commandLong = QString::fromAscii(cl).toUtf8();
    description = ki18n(desc);
    this->hasFreeArgs = hasFreeArgs;
    this->freeArgs = args;
}

void AkabeiOperation::addOption(AkabeiOption& opt)
{
    options.insert(opt.name, opt);
}

bool AkabeiOperation::isOptionSupported(APM::OptionName name)
{
    return options.contains(name);
}

/*
 * Actual parsing
 */
void CmdLine::parse(int argc, char** argv)
{
    KAboutData aboutData("akabei", 0, ki18n("Akabei"),
                         QByteArray("0.0.1"),
                         ki18n("Chakra's CLI package manager"),
                         KAboutData::License_GPL,
                         ki18n("(C) 2011 Lukas Appelhans"),
                         ki18n("<a href=\"mailto:boom1992@chakra-project.org\">boom1992@chakra-project.org</a>"));
    
    aboutData.addAuthor(ki18n("Lukas Appelhans"), ki18n("Maintainer"), "boom1992@chakra-project.org");
    KCmdLineArgs::init(argc, argv, &aboutData);
    KCmdLineOptions koptions;
    
    /*
     * Adds all the types
     */
    koptions.add("D", ki18n("Database"));
    koptions.add("S", ki18n("Install"));
    koptions.add("U", ki18n("Upgrade"));
    koptions.add("R", ki18n("Remove"));
    koptions.add("Q", ki18n("Query"));
    
    /*
     * Adds all the operations
     */
    foreach (AkabeiOperation op, acceptedOperations.values()) {
        
        if (!op.commandLong.isEmpty()) {
            if (!op.commandShort.isEmpty()) {
                koptions.add(op.commandShort);
            }
            koptions.add(op.commandLong, op.description);
        }
        else {
            koptions.add(op.commandShort, op.description);
        }
    }
    
    /*
     * Adds all the option with <argument> if they require one
     * TODO: make <argument> more explicative of its nature (package, group, filename, ...)
     */
    foreach (AkabeiOption opt, acceptedOptions) {
        QByteArray newcomlong = opt.commandLong;
        if (opt.hasArg) {
            newcomlong += " <argument>";
        }
        if (!opt.commandShort.isEmpty()) {
            koptions.add(opt.commandShort);
        }
        koptions.add(newcomlong, opt.description);
    }
    
    /*
     * Free arguments at the end
     */
    koptions.add("+[arg1]", ki18n("An optional argument 'arg1'"));
    
    /*
     * Parsing!
     */
    KCmdLineArgs::addCmdLineOptions(koptions);
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    
    APM::OperationType type = APM::NoType;
    m_operation.name = APM::None;
    QList<QByteArray> checkops, checkopts;
    
    /*
     * These are considered separately and when found, they surpass any other operation that may be present.
     */
    if (args->isSet("h")) {
        m_operation = acceptedOperations.value("h");
    } else if (args->isSet("v")) {
        m_operation = acceptedOperations.value("v");
    }
    else {
        for (QHash<QByteArray, APM::OperationType>::iterator it = typechars.begin(); it != typechars.end(); it++) {
            if (args->isSet(it.key())) {
                if (type != APM::NoType) {
363
                    throw CmdLineException("multiple types present.");
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
                }
                
                type = it.value();
            
                /*
                 * Take in mind that more operations and more options may share the same command
                 * so we have to consider all the possibilities for whatever we find on the command line
                 */
                foreach (QByteArray command, acceptedOperations.uniqueKeys()) {
                    if (command.isEmpty()) {
                        continue;
                    }
                    
                    /*
                     * Looks up all the operations with that command in search of one with the right type.
                     * If found, set it as operation.
                     */
                    if (args->isSet(command)) {
382
                        qDebug() << "found" << command;
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
                        bool found = false;
                        
                        foreach (AkabeiOperation op, acceptedOperations.values(command)) {
                            if (op.type == type) {
                                found = true;
                                m_operation.set(op);
                                
                                /* Save it so it isn't searched again as an option */
                                checkops.append(command);
                            }
                        }
                        
                        /*
                         * If not found, that command can represent an option!
                         * So save it for later inspection
                         */
                        if (!found) {
                            checkopts.append(command);
                        }
                    }
                }
            }
        }
    }
    
    if (m_operation.name == APM::None) {
409
        throw CmdLineException("no operation specified.");
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    }
    
    foreach (AkabeiOption opt, acceptedOptions) {
        QByteArray command = (opt.commandShort.isEmpty()) ? opt.commandLong : opt.commandShort;
        
        /* 
         * If checkops contains the command, we already decided it's an operation, so go on
         */
        if (!checkops.contains(command) && args->isSet(command)) {
            /*
             * if it was one of the commands we were unsure about, now we're sure
             * (if command is not present, nothing is done anyway)
             */
            checkopts.removeOne(command);
            
            if (!m_operation.isOptionSupported(opt.name)) {
426
                throw CmdLineException("invalid option for this operation");
427 428 429 430 431 432 433 434 435 436 437 438
            }
            
            /*
             * Gets arguments associated with the option
             */
            QStringList optargs = args->getOptionList(command);

            /*
             * Remember, if it's not an option args it can be an argument to the operation
             * so we're not really sure an error has been made, unless the operation doesn't admit any argument
             */
            if (!optargs.isEmpty() && !opt.hasArg && !m_operation.hasFreeArgs) {
439 440
                QString message = "the option \"" + command + "\" must not have an argument.";
                throw CmdLineException(message.toUtf8().data());
441 442 443 444 445 446
            }
            
            /*
             * In this case, we're sure :)
             */
            if (optargs.isEmpty() && opt.hasArg) {
447 448
                QString message = "missing argument for the option \"" + command + "\"";
                throw CmdLineException(message.toUtf8().data());
449 450 451 452 453 454 455 456 457 458 459
            }
            
            opt.args = optargs;
            m_options.insert(opt.name, opt);
        }
    }
    
    /*
     * If that strange command wasn't an option, then it was something wrong
     */
    if (!checkopts.isEmpty()) {
460 461 462
        qDebug() << "this";
        QString command = "the operation \"" + checkops.takeFirst() + "\" is out of context.";
        throw CmdLineException(command.toUtf8().data());
463 464 465 466 467 468 469
    }
    
    for (int i = 0; i < args->count(); i++) {
        m_freeArgs << args->arg(i);
    }
    
    if (!m_freeArgs.isEmpty() && !m_operation.hasFreeArgs) {
470
        throw CmdLineException("unexpected free arguments.");
471 472 473
    }
    
    if (m_freeArgs.isEmpty() && m_operation.hasFreeArgs) {
474
        throw CmdLineException("free arguments required but not present.");
475 476 477
    }
    
    args->clear(); /* frees up memory */
478 479
    
    secondParse(argc, argv);
480 481 482
    parsed = true;
}

483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
/*
 * This function handles all the parsing which can't be handled using KCmdLineArgs
 * In particular, checks if the operation is repeated more than one, which isn't accepted
 */
void CmdLine::secondParse(int argc, char** argv)
{
    QStringList cmdline;
    
    for (int i = 1; i < argc; i++) {
        QString part = QString::fromAscii(argv[i]);
        
        if (part.size() < 2) {
            continue;
        }
        
        /* long command */
        if (part.at(0) == '-' && part.at(1) == '-') {
            cmdline << part.remove(0, 2);
        /* short command: takes each letter separately */
        } else if (part.at(0) == '-') {
            part.remove(0, 1);
            
            /* The only short commands with two letters is treated separately to avoid problems */
            if (part.contains("cc")) {
                if (part.count("cc") > 1) {
                    throw CmdLineException("can't accept linked operations.");
                } else {
                    part.remove("cc");
                }
            }
            
            for (int ch = 0; ch < part.length(); ch++) {
                cmdline << QString(part[ch]);
            }
        }
    }
    
    int occurrences = cmdline.count(m_operation.commandLong) + cmdline.count(m_operation.commandShort);
    if (occurrences > 1) {
        throw CmdLineException("can't accept linked operations.");
    }
    
    foreach (AkabeiOption opt, m_options.values()) {
        
        /* The only options allowed to be repeated several times */
        if (opt.name == APM::Ignore || opt.name == APM::IgnoreGroup) {
            continue;
        }
        
        occurrences = cmdline.count(opt.commandLong) + cmdline.count(opt.commandShort);
        if (occurrences > 1) {
            throw CmdLineException("Can't repeat this option twice!");
        }
    }
}

539 540 541 542 543
APM::OperationType CmdLine::type()
{
    if (!parsed) {
        throw CmdLineException("Command line not parsed.");
    }
544

545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
    return m_operation.type;
}

APM::OperationName CmdLine::operation()
{
    if (!parsed) {
        throw CmdLineException("Command line not parsed.");
    }
    
    return m_operation.name;
}

QStringList CmdLine::freeArgs()
{
    if (!parsed) {
        throw CmdLineException("Command line not parsed.");
    }
    
    return m_freeArgs;
}

QHash< APM::OptionName, AkabeiOption > CmdLine::options()
{
    if (!parsed) {
        throw CmdLineException("Command line not parsed.");
    }
    
    return m_options;
}