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 470 471 472 473 474 475 476 477 478 479 480 481 482 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 539 540 541 542 543 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 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
|
/*
* tagged collection - Experimental programs to test and study tagged collections
*
* Copyright (C) 2003,2004,2005,2006 Enrico Zini
*
* 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.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#define APPNAME PACKAGE
#else
#warning No config.h found: using fallback values
#define APPNAME __FILE__
#define VERSION "unknown"
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h> // getenv
#include <errno.h>
#include <tagcoll/stringf.h>
#include <tagcoll/Exception.h>
#include <tagcoll/Commandline.h>
#include <tagcoll/CardinalityStore.h>
#include <tagcoll/SmartHierarchy.h>
#include <tagcoll/Consumer.h>
#include <tagcoll/Filter.h>
#include <tagcoll/InputMerger.h>
#include <tagcoll/Implications.h>
#include <tagcoll/Filters.h>
#include <tagcoll/Patches.h>
#include <tagcoll/DerivedTags.h>
#include <tagcoll/ItemGrouper.h>
#include <tagcoll/StdioParserInput.h>
#include <tagcoll/TextFormat.h>
#include <tagcoll/Serializer.h>
#include <tagcoll/Expression.h>
#include <algorithm>
#include <iostream>
#include "TagcollOptions.h"
using namespace std;
using namespace Tagcoll;
bool isdir(const std::string& file)
{
struct stat st;
if (stat(file.c_str(), &st) == -1)
throw SystemException(errno, "trying to stat file " + file);
return S_ISDIR(st.st_mode);
}
void printItems(const set<string>& items, const string& prefix = "")
{
for (set<string>::const_iterator i = items.begin();
i != items.end(); i++)
{
printf("%.*s%.*s\n", PFSTR(prefix), PFSTR(*i));
}
}
void printNode(HierarchyNode<string, string>* node, string prefix = "")
{
OpSet<string> items = node->getItems();
if (!items.empty())
{
printItems(items, prefix + ": ");
// } else {
// printf("%.*s: no items\n", PFSTR(prefix));
}
if (prefix.size() > 0 && prefix[prefix.size() - 1] != '/')
prefix += '/';
for (HierarchyNode<string, string>::iterator i = node->begin();
i != node->end(); i++)
{
printNode(*i, prefix + (*i)->tag());
}
}
OpSet<string> getItems(HierarchyNode<string, string>* node)
{
OpSet<string> items = node->getItems();
for (HierarchyNode<string, string>::iterator i = node->begin();
i != node->end(); i++)
items += getItems(*i);
return items;
}
void readCollection(const string& file, Consumer<string, string>& builder)
throw (FileException, ParserException)
{
TrivialConverter<string, string> conv;
if (file == "-")
{
StdioParserInput input(stdin, "<stdin>");
TextFormat<string, string>::parse(conv, conv, input, builder);
}
else
{
StdioParserInput input(file);
TextFormat<string, string>::parse(conv, conv, input, builder);
}
}
PatchList<string, string> readPatches(const string& file)
throw (FileException, ParserException)
{
TrivialConverter<string, string> conv;
if (file == "-")
{
StdioParserInput input(stdin, "<stdin>");
return TextFormat<string, string>::parsePatch(conv, conv, input);
}
else if (isdir(file))
{
PatchList<string, string> patches;
DIR* dir = opendir(file.c_str());
if (dir == NULL)
throw SystemException(errno, "reading directory " + file);
while (struct dirent* d = readdir(dir))
{
if (d->d_name[0] == '.')
continue;
StdioParserInput input(file + '/' + d->d_name);
patches.addPatch(TextFormat<string, string>::parsePatch(conv, conv, input));
}
closedir(dir);
return patches;
}
else
{
StdioParserInput input(file);
return TextFormat<string, string>::parsePatch(conv, conv, input);
}
}
void parseDerivedTags(ParserInput& in, DerivedTags& output)
{
string tag;
string expr;
int c;
enum {TAG, TAGCOLON, SEXPR, EXPR} state = TAG;
int line = 1;
while ((c = in.nextChar()) != ParserInput::Eof)
{
if (c == '\n')
{
if (tag.size() > 0 && expr.size() > 0)
output.add(tag, expr);
else
fprintf(stderr, "In derived tags file, ignoring incomplete line %d.\n", line);
tag = string();
expr = string();
state = TAG;
line++;
} else
switch (state)
{
// Read item
case TAG:
switch (c)
{
case ':':
state = TAGCOLON;
break;
default:
tag += c;
break;
}
break;
// After colon on item
case TAGCOLON:
switch (c)
{
case ' ':
case '\t':
state = SEXPR;
break;
case ':':
tag += c;
break;
default:
tag += ':';
tag += c;
state = EXPR;
break;
}
break;
// Space before tag
case SEXPR:
switch (c)
{
case ' ':
case '\t':
break;
default:
expr += c;
state = EXPR;
break;
}
break;
// Read tag
case EXPR:
expr += c;
break;
}
}
}
void readDerivedTags(const string& file, DerivedTags& derivedTags)
throw (FileException)
{
if (file == "-")
{
StdioParserInput input(stdin, "<stdin>");
parseDerivedTags(input, derivedTags);
}
else
{
StdioParserInput input(file);
parseDerivedTags(input, derivedTags);
}
}
template<typename ITEM, typename TAG>
class ItemsOnly : public Filter<ITEM, TAG>
{
protected:
virtual void consumeItemUntagged(const ITEM& item)
{
this->consumer->consume(item);
}
virtual void consumeItem(const ITEM& item, const OpSet<TAG>& tags)
{
this->consumer->consume(item);
}
virtual void consumeItemsUntagged(const OpSet<ITEM>& items)
{
this->consumer->consume(items);
}
virtual void consumeItem(const OpSet<ITEM>& items, const OpSet<TAG>& tags)
{
this->consumer->consume(items);
}
public:
ItemsOnly() {}
ItemsOnly(Consumer<ITEM, TAG>& cons) : Filter<ITEM, TAG>(cons) {}
};
template<typename ITEM, typename TAG>
class Reverser : public Consumer<ITEM, TAG>
{
protected:
Consumer<TAG, ITEM>* consumer;
TAG reversedNull;
virtual void consumeItemUntagged(const ITEM& item)
{
consumer->consume(reversedNull, OpSet<ITEM>() + item);
}
virtual void consumeItem(const ITEM& item, const OpSet<TAG>& tags)
{
consumer->consume(tags, OpSet<ITEM>() + item);
}
virtual void consumeItemsUntagged(const OpSet<ITEM>& items)
{
consumer->consume(reversedNull, items);
}
virtual void consumeItem(const OpSet<ITEM>& items, const OpSet<TAG>& tags)
{
consumer->consume(tags, items);
}
public:
Reverser(Consumer<TAG, ITEM>& cons, const TAG& reversedNull = TAG()) :
consumer(&cons), reversedNull(reversedNull) {}
};
class Reader
{
// Prepare the input filter chain
FilterChain<string, string> filters;
Substitute<string, string> substitutions;
PatchList<string, string> patches;
Implications<string> implications;
DerivedTags derivedTags;
AddImplied<string, string> addImplied;
RemoveImplied<string, string> removeImplied;
AddDerived<string> addDerived;
RemoveDerived<string> removeDerived;
UnfacetedRemover<string> unfacetedRemover;
FilterTagsByExpression<string, string> filterByExpression;
public:
Reader(commandline::TagcollOptions& opts)
: addImplied(implications), removeImplied(implications),
addDerived(derivedTags), removeDerived(derivedTags),
unfacetedRemover("::"), filterByExpression("")
{
if (opts.inputGroup.rename->boolValue())
{
readCollection(opts.inputGroup.rename->stringValue(), substitutions.substitutions());
filters.appendFilter(substitutions);
}
if (opts.inputGroup.patch->boolValue())
{
patches = readPatches(opts.inputGroup.patch->stringValue());
filters.appendFilter(patches);
}
if (opts.inputGroup.extimpl->boolValue())
{
readCollection(opts.inputGroup.extimpl->stringValue(), implications);
// Pack the structure for faster expansions
implications.pack();
}
if (opts.inputGroup.derived->boolValue())
readDerivedTags(opts.inputGroup.derived->stringValue(), derivedTags);
// Intermix implications and derived tags as seems best
bool compressOutput = (opts.lastCommand()->name() == "copy" && !opts.outputGroup.redundant->boolValue());
bool hasImpl = opts.inputGroup.extimpl->boolValue();
bool hasDerv = opts.inputGroup.derived->boolValue();
if (compressOutput)
{
if (hasDerv)
{
// Expand implications
if (hasImpl) filters.appendFilter(addImplied);
// Remove derived tags computing them using the expanded tag set
filters.appendFilter(removeDerived);
}
// Compress implications
if (hasImpl) filters.appendFilter(removeImplied);
} else {
// Expand implications
if (hasImpl) filters.appendFilter(addImplied);
// Add derived tags computing them using the expanded tag set
if (hasDerv)
{
filters.appendFilter(addDerived);
// Add further tags implicated by the derived tags
if (hasImpl) filters.appendFilter(addImplied);
}
}
if (opts.inputGroup.rmunfaceted->boolValue())
filters.appendFilter(unfacetedRemover);
if (opts.inputGroup.rmtags->boolValue())
{
filterByExpression.setExpression(not Expression(opts.inputGroup.rmtags->stringValue()));
filters.appendFilter(filterByExpression);
}
}
void output(const string& file, Consumer<string, string>& cons)
{
filters.setConsumer(cons);
readCollection(file, filters);
}
void output(commandline::TagcollOptions& opts, Consumer<string, string>& cons)
{
if (opts.hasNext())
while (opts.hasNext())
output(opts.next(), cons);
else
output("-", cons);
}
};
class Writer : public Consumer<string, string>
{
TrivialConverter<string, string> conv;
TextFormat<string, string> output;
ItemGrouper<string, string>* grouper;
bool itemsOnly;
protected:
/// Process an untagged item
virtual void consumeItemUntagged(const string& item)
{
if (grouper)
grouper->consume(item);
else
output.consume(item);
}
/// Process a tagged item, with its tags
virtual void consumeItem(const string& item, const OpSet<string>& tags)
{
if (itemsOnly)
consumeItemUntagged(item);
else if (grouper)
grouper->consume(item, tags);
else
output.consume(item, tags);
}
/// Process a set of items, all with no tags
virtual void consumeItemsUntagged(const OpSet<string>& items)
{
if (grouper)
grouper->consume(items);
else
// Explicitly split groups
for (OpSet<string>::const_iterator i = items.begin();
i != items.end(); i++)
output.consume(*i);
}
/// Process a set of items identically tagged, with their tags
virtual void consumeItems(const OpSet<string>& items, const OpSet<string>& tags)
{
if (itemsOnly)
consumeItemsUntagged(items);
else if (grouper)
grouper->consume(items, tags);
else
// Explicitly split groups
for (OpSet<string>::const_iterator i = items.begin();
i != items.end(); i++)
output.consume(*i, tags);
}
public:
Writer(commandline::TagcollOptions& opts)
: output(conv, conv, stdout), grouper(0)
{
if (opts.outputGroup.group->boolValue())
grouper = new ItemGrouper<string, string>;
itemsOnly = opts.outputGroup.itemsOnly->boolValue();
}
~Writer()
{
// Flush output if needed
if (grouper)
{
grouper->output(output);
delete grouper;
}
}
};
int main(int argc, const char* argv[])
{
commandline::TagcollOptions opts;
try {
opts.parse(argc, argv);
if (!opts.lastCommand())
throw commandline::BadOption("could not understand the command to execute");
Reader reader(opts);
// Perform the correct operation
if (opts.helpGroup.help->boolValue())
{
// Provide help as requested
commandline::Help help(APPNAME, VERSION);
commandline::OptionParser* o = opts.lastCommand();
if (o && !o->name().empty())
// Help on a specific command
help.outputHelp(cout, *o);
else
// General help
help.outputHelp(cout, opts);
}
else if (opts.helpGroup.version->boolValue())
{
// Print the program version
commandline::Help help(APPNAME, VERSION);
help.outputVersion(cout);
}
else if (opts.lastCommand() == &opts.generic)
{
commandline::Help help(APPNAME, VERSION);
help.outputHelp(cout, opts);
}
else if (opts.lastCommand() == &opts.help)
{
commandline::Help help(APPNAME, VERSION);
commandline::OptionParser* o = 0;
if (opts.hasNext())
o = opts.command(opts.next());
if (o)
// Help on a specific command
help.outputHelp(cout, *o);
else
// General help
help.outputHelp(cout, opts);
}
else if (opts.lastCommand() == &opts.implications)
{
CardinalityStore<string, string> coll;
reader.output(opts, coll);
Implications<string> newImpls;
// Find tag implications
OpSet<string> allTags = coll.getAllTags();
for (OpSet<string>::const_iterator t = allTags.begin();
t != allTags.end(); t++)
{
OpSet<string> implied = coll.getImpliedBy(*t);
if (!implied.empty())
newImpls.consume(*t, implied);
}
newImpls.pack();
TrivialConverter<string, string> conv;
TextFormat<string, string> output(conv, conv, stdout);
if (opts.outputGroup.redundant->boolValue())
newImpls.outputFull(output);
else
newImpls.output(output);
}
else if (opts.lastCommand() == &opts.hierarchy)
{
int flattenThreshold = 0;
if (opts.hierarchyGroup.flatten->boolValue())
flattenThreshold = opts.hierarchyGroup.flatten->intValue();
CardinalityStore<string, string> coll;
reader.output(opts, coll);
if (opts.hierarchyGroup.filter->boolValue())
coll.removeTagsWithCardinalityLessThan(opts.hierarchyGroup.filter->intValue());
// Default operation: build the smart hierarchy
HierarchyNode<string, string>* root =
new SmartHierarchyNode<string, string>("_top", coll, flattenThreshold);
printNode(root, "/");
}
else if (opts.lastCommand() == &opts.cleanhierarchy)
{
int flattenThreshold = 0;
if (opts.hierarchyGroup.flatten->boolValue())
flattenThreshold = opts.hierarchyGroup.flatten->intValue();
CardinalityStore<string, string> coll;
reader.output(opts, coll);
if (opts.hierarchyGroup.filter->boolValue())
coll.removeTagsWithCardinalityLessThan(opts.hierarchyGroup.filter->intValue());
// Default operation: build the smart hierarchy
HierarchyNode<string, string>* root = new CleanSmartHierarchyNode<string, string>("_top", coll, flattenThreshold);
printNode(root, "/");
}
else if (opts.lastCommand() == &opts.diff)
{
InputMerger<string, string> merger1;
reader.output(opts.next(), merger1);
InputMerger<string, string> merger2;
reader.output(opts.next(), merger2);
PatchList<string, string> newpatches;
newpatches.addPatch(merger1, merger2);
TrivialConverter<string, string> conv;
TextFormat<string, string>::outputPatch(conv, conv, newpatches, stdout);
}
else if (opts.lastCommand() == &opts.related)
{
string item = opts.next();
InputMerger<string, string> merger;
reader.output(opts, merger);
int maxdist = 0;
if (opts.related.distance->boolValue())
maxdist = opts.related.distance->intValue();
// Split the items on commas
string splititem;
set<string> splititems;
for (string::const_iterator c = item.begin();
c != item.end(); c++)
if (*c == ',')
{
if (!merger.hasItem(splititem))
{
fprintf(stderr, "Item \"%.*s\" does not exist in the collection\n", PFSTR(splititem));
return 1;
}
splititems.insert(splititem);
splititem = string();
} else
splititem += *c;
if (!merger.hasItem(splititem))
{
fprintf(stderr, "Item \"%.*s\" does not exist in the collection\n", PFSTR(splititem));
return 1;
}
splititems.insert(splititem);
// Get the tagset as the intersection of the tagsets of all input items
set<string>::const_iterator i = splititems.begin();
OpSet<string> ts = merger.getTags(*i);
for (++i; i != splititems.end(); i++)
ts = ts ^ merger.getTags(*i);
if (ts.empty())
{
if (splititems.size() > 1)
fprintf(stderr, "The items %.*s are unrelated: cannot find a barycenter to start computing relationships from.\n", PFSTR(item));
else
fprintf(stderr, "The items %.*s has no tags attached.\n", PFSTR(item));
return 1;
}
// Build a full TagCollection
CardinalityStore<string, string> coll;
merger.output(coll);
printItems(coll.getItemsExactMatch(ts));
if (maxdist)
{
// Get the related tagsets
list< OpSet<string> > rel = coll.getRelatedTagsets(ts, maxdist);
// Print the output list
for (list< OpSet<string> >::const_iterator i = rel.begin();
i != rel.end(); i++)
printItems(coll.getItemsExactMatch(*i));
}
}
else if (opts.lastCommand() == &opts.reverse)
{
string revnull;
if (opts.reverse.untaggedTag->boolValue())
revnull = opts.reverse.untaggedTag->stringValue();
InputMerger<string, string> reversed;
Reverser<string, string> reverser(reversed, revnull);
reader.output(opts, reverser);
Writer writer(opts);
reversed.output(writer);
}
else if (opts.lastCommand() == &opts.copy)
{
Writer writer(opts);
reader.output(opts, writer);
}
else if (opts.lastCommand() == &opts.findspecials)
{
int flattenThreshold = 0;
if (opts.hierarchyGroup.flatten->boolValue())
flattenThreshold = opts.hierarchyGroup.flatten->intValue();
CardinalityStore<string, string> coll;
reader.output(opts, coll);
if (opts.hierarchyGroup.filter->boolValue())
coll.removeTagsWithCardinalityLessThan(opts.hierarchyGroup.filter->intValue());
// Default operation: build the smart hierarchy
SmartHierarchyNode<string, string> root("_top", coll, flattenThreshold);
OpSet<string> seen;
for (HierarchyNode<string, string>::iterator i = root.begin();
i != root.end(); i++)
{
OpSet<string> items = getItems(*i);
// Find the items in this branch that are not present in
// any of the previous ones
OpSet<string> newItems;
if (!seen.empty())
{
for (OpSet<string>::const_iterator j = items.begin();
j != items.end(); j++)
{
OpSet<string> tags = coll.getTags(*j) ^ seen;
if (tags.empty())
newItems += *j;
}
printf("%.*s: %d items, %d special items:\n",
PFSTR((*i)->tag()), items.size(), newItems.size());
int indent = (*i)->tag().size() + 2;
for (OpSet<string>::const_iterator j = newItems.begin(); j != newItems.end(); j++)
printf("%*s%.*s\n", indent, "", PFSTR(*j));
}
seen += (*i)->tag();
}
}
else if (opts.lastCommand() == &opts.grep)
{
Writer writer(opts);
FilterItemsByExpression<string, string> filter(writer, opts.next());
reader.output(opts, filter);
}
else
throw commandline::BadOption(string("unhandled command ") +
(opts.lastCommand() ? opts.lastCommand()->name() : "(null)"));
return 0;
} catch (commandline::BadOption& e) {
cerr << e.desc() << endl;
commandline::Help help(APPNAME, VERSION);
if (opts.lastCommand())
{
help.outputHelp(cerr, *opts.lastCommand());
} else {
help.outputHelp(cerr, opts);
}
exit(1);
} catch (Exception& e)
{
fprintf(stderr, "%s: %.*s\n", e.type(), PFSTR(e.desc()));
return 1;
}
}
// vim:set ts=4 sw=4:
|