got things a bit closer to right, but there is still a nasty problem on
[feisty_meow.git] / nucleus / library / filesystem / directory_tree.cpp
1 /*****************************************************************************\
2 *                                                                             *
3 *  Name   : directory_tree                                                    *
4 *  Author : Chris Koeritz                                                     *
5 *                                                                             *
6 *******************************************************************************
7 * Copyright (c) 2004-$now By Author.  This program is free software; you can  *
8 * redistribute it and/or modify it under the terms of the GNU General Public  *
9 * License as published by the Free Software Foundation; either version 2 of   *
10 * the License or (at your option) any later version.  This is online at:      *
11 *     http://www.fsf.org/copyleft/gpl.html                                    *
12 * Please send any updates to: fred@gruntose.com                               *
13 \*****************************************************************************/
14
15 #include "directory.h"
16 #include "directory_tree.h"
17 #include "filename.h"
18 #include "filename_list.h"
19 #include "filename_tree.h"
20
21 #include <basis/functions.h>
22 #include <basis/contracts.h>
23 #include <loggers/program_wide_logger.h>
24 #include <structures/object_packers.h>
25 #include <structures/string_array.h>
26 #include <textual/parser_bits.h>
27 #include <textual/string_manipulation.h>
28
29 #include <stdio.h>
30
31 using namespace basis;
32 using namespace loggers;
33 using namespace nodes;
34 using namespace structures;
35 using namespace textual;
36
37 //#define DEBUG_DIRECTORY_TREE
38   // uncomment for noisier version.
39
40 #undef LOG
41 #define LOG(to_print) CLASS_EMERGENCY_LOG(program_wide_logger::get(), to_print)
42 //printf("%s::%s: %s\n", static_class_name(), func, astring(to_print).s())
43
44 //////////////
45
46 namespace filesystem {
47
48 class dir_tree_iterator : public filename_tree::iterator
49 {
50 public:
51   filename_tree *_current;
52
53   dir_tree_iterator(const filename_tree *initial,
54       tree::traversal_directions dir)
55   : filename_tree::iterator(initial, dir), _current(NIL) {}
56 };
57
58 //////////////
59
60 directory_tree::directory_tree()
61 : _scanned_okay(false),
62   _path(new astring),
63   _pattern(new astring),
64   _real_tree(new filename_tree),
65   _ignore_files(false),
66   _creator(new fname_tree_creator)
67 {
68 }
69
70 directory_tree::directory_tree(const astring &path, const char *pattern,
71     bool ignore_files)
72 : _scanned_okay(false),
73   _path(new astring(path)),
74   _pattern(new astring(pattern)),
75   _real_tree(NIL),
76   _ignore_files(ignore_files),
77   _creator(new fname_tree_creator)
78 {
79   reset(path, pattern);
80 }
81
82 directory_tree::~directory_tree()
83 {
84   _scanned_okay = false;
85   WHACK(_path);
86   WHACK(_pattern);
87   WHACK(_real_tree);
88   WHACK(_creator);
89 }
90
91 const astring &directory_tree::path() const { return *_path; }
92
93 int directory_tree::packed_size() const
94 {
95   return 2 * PACKED_SIZE_INT32
96       + _path->packed_size()
97       + _pattern->packed_size()
98       + _real_tree->recursive_packed_size();
99 }
100
101 void directory_tree::pack(byte_array &packed_form) const
102 {
103   attach(packed_form, int(_scanned_okay));
104   attach(packed_form, int(_ignore_files));
105   _path->pack(packed_form);
106   _pattern->pack(packed_form);
107   _real_tree->recursive_pack(packed_form);
108 }
109
110 bool directory_tree::unpack(byte_array &packed_form)
111 {
112   int temp;
113   if (!detach(packed_form, temp)) return false;
114   _scanned_okay = temp;
115   if (!detach(packed_form, temp)) return false;
116   _ignore_files = temp;
117   if (!_path->unpack(packed_form)) return false;
118   if (!_pattern->unpack(packed_form)) return false;
119   WHACK(_real_tree);
120   _real_tree = (filename_tree *)packable_tree::recursive_unpack
121       (packed_form, *_creator);
122   if (!_real_tree) {
123     _real_tree = new filename_tree;  // reset it.
124     return false;
125   }
126   return true;
127 }
128
129 void directory_tree::text_form(astring &target, bool show_files)
130 {
131   dir_tree_iterator *ted = start(directory_tree::prefix);
132     // create our iterator to do a prefix traversal.
133
134   int depth;  // current depth in tree.
135   filename curr;  // the current path the iterator is at.
136   string_array files;  // the filenames held at the iterator.
137
138   while (current(*ted, curr, files)) {
139     // we have a good directory to show.
140     directory_tree::depth(*ted, depth);
141     target += string_manipulation::indentation(depth * 2) + astring("[")
142         + curr.raw() + "]" + parser_bits::platform_eol_to_chars();
143     if (show_files) {
144       astring names;
145       for (int i = 0; i < files.length(); i++) names += files[i] + " ";
146       if (names.length()) {
147         astring split;
148         string_manipulation::split_lines(names, split, depth * 2 + 2);
149         target += split + parser_bits::platform_eol_to_chars();
150       }
151     }
152
153     // go to the next place.
154     next(*ted);
155   }
156
157   throw_out(ted);
158 }
159
160 void directory_tree::traverse(const astring &path, const char *pattern,
161     filename_tree &add_to)
162 {
163   FUNCDEF("traverse");
164   // prepare the current node.
165   add_to._dirname = filename(path, astring::empty_string());
166   add_to._files.reset();
167 #ifdef DEBUG_DIRECTORY_TREE
168   LOG(astring("working on node ") + add_to._dirname);
169 #endif
170
171   // open the directory.
172   directory curr(path, "*");
173   if (!curr.good()) return;
174
175   if (!_ignore_files) {
176     // add all the files to the current node.
177     directory curr_stringent(path, pattern);
178     add_to._files = curr_stringent.files();
179   }
180
181   // now iterate across the directories here and add a sub-node for each one,
182   // and recursively traverse that sub-node also.
183   const string_array &dirs = curr.directories();
184   for (int i = 0; i < dirs.length(); i++) {
185     filename_tree *new_branch = NIL;
186     astring new_path = path + filename::default_separator() + dirs[i];
187 #ifdef DEBUG_DIRECTORY_TREE
188     LOG(astring("seeking path: ") + new_path);
189 #endif
190     if (!filename(new_path).is_normal()) {
191 //#ifdef DEBUG_DIRECTORY_TREE
192       LOG(astring("bailing on weird dir: ") + new_path);
193 //#endif
194       continue;  // only regular directories please.
195     }
196     for (int q = 0; q < add_to.branches(); q++) {
197       filename_tree *curr_kid = (filename_tree *)add_to.branch(q);
198 #ifdef DEBUG_DIRECTORY_TREE
199       LOG(astring("curr kid: ") + curr_kid->_dirname);
200 #endif
201       if (filename(new_path).raw().iequals(filename
202           (curr_kid->_dirname).raw())) {
203         new_branch = curr_kid;
204 #ifdef DEBUG_DIRECTORY_TREE
205         LOG(astring("using existing branch for ") + new_path);
206 #endif
207         break;
208       }
209     }
210     if (!new_branch) {
211 #ifdef DEBUG_DIRECTORY_TREE
212       LOG(astring("adding new branch for ") + new_path);
213 #endif
214       new_branch = new filename_tree;
215       add_to.attach(new_branch);
216       new_branch->_depth = add_to._depth + 1;
217     }
218 #ifdef DEBUG_DIRECTORY_TREE
219     LOG(astring("traversing sub-node ") + new_path);
220 #endif
221     traverse(new_path, pattern, *new_branch);
222   }
223 }
224
225 bool directory_tree::reset(const astring &path, const char *pattern)
226 {
227   _scanned_okay = false;
228   WHACK(_real_tree);
229   *_path = path;
230   *_pattern = pattern;
231   _real_tree = new filename_tree;
232
233   // check that the top-level is healthy.
234   directory curr(path, "*");
235   if (!curr.good()) return false;
236     // our only exit condition; other directories might not be accessible
237     // underneath, but the top one must be accessible for us to even start
238     // the scanning.
239
240   traverse(path, pattern, *_real_tree);
241   _scanned_okay = true;;
242   return true;
243 }
244
245 dir_tree_iterator *directory_tree::start_at(filename_tree *start,
246     traversal_types type) const
247 {
248   // translate to the lower level traversal enum.
249   tree::traversal_directions dir = tree::prefix;
250   if (type == infix) dir = tree::infix;
251   else if (type == postfix) dir = tree::postfix;
252
253   return new dir_tree_iterator(start, dir);
254 }
255
256 dir_tree_iterator *directory_tree::start(traversal_types type) const
257 {
258   // translate to the lower level traversal enum.
259   tree::traversal_directions dir = tree::prefix;
260   if (type == infix) dir = tree::infix;
261   else if (type == postfix) dir = tree::postfix;
262
263   return new dir_tree_iterator(_real_tree, dir);
264 }
265
266 bool directory_tree::jump_to(dir_tree_iterator &scanning,
267     const astring &sub_path)
268 {
269   FUNCDEF("jump_to");
270   string_array pieces;
271   filename(sub_path).separate(pieces);
272   for (int i = 0; i < pieces.length(); i++) {
273     filename_tree *curr = dynamic_cast<filename_tree *>(scanning.current());
274 #ifdef DEBUG_DIRECTORY_TREE
275     LOG(astring("at ") + curr->_dirname.raw());
276 #endif
277     string_array sub_pieces = pieces.subarray(i, i);
278     filename curr_path;
279     curr_path.join(sub_pieces);
280     curr_path = filename(curr->_dirname.raw() + filename::default_separator()
281         + curr_path.raw());
282 #ifdef DEBUG_DIRECTORY_TREE
283     LOG(astring("made curr path ") + curr_path.raw());
284 #endif
285     if (!curr) return false;
286     bool found_it = false;
287     for (int j = 0; j < curr->branches(); j++) {
288       filename_tree *sub = dynamic_cast<filename_tree *>(curr->branch(j));
289 #ifdef DEBUG_DIRECTORY_TREE
290       LOG(astring("looking at ") + sub->_dirname.raw());
291 #endif
292       if (sub->_dirname.compare_prefix(curr_path)) {
293         // this part matches!
294         scanning.push(sub);
295 #ifdef DEBUG_DIRECTORY_TREE
296         LOG(astring("found at ") + sub->_dirname.raw());
297 #endif
298         found_it = true;
299         break;
300       }
301     }
302     if (!found_it) {
303 #ifdef DEBUG_DIRECTORY_TREE
304       LOG(astring("could not find ") + curr_path.raw());
305 #endif
306       return false;
307     }
308   }
309   return true;
310 }
311
312 filename_tree *directory_tree::goto_current(dir_tree_iterator &scanning)
313 {
314   if (!scanning._current) {
315     // this one hasn't been advanced yet, or it's already over with.
316     scanning._current = (filename_tree *)scanning.next();
317   }
318   // now check that we're healthy.
319   if (!scanning._current) return NIL;  // all done.
320
321   // cast the tree to the right type.
322   return dynamic_cast<filename_tree *>(scanning._current);
323 }
324
325 bool directory_tree::current_dir(dir_tree_iterator &scanning,
326     filename &dir_name)
327 {
328   dir_name = astring::empty_string();
329   filename_tree *tof = goto_current(scanning);
330   if (!tof) return false;
331   dir_name = tof->_dirname;
332   return true;
333 }
334
335 bool directory_tree::current(dir_tree_iterator &scanning,
336     filename &dir_name, string_array &to_fill)
337 {
338   // clear any existing junk.
339   dir_name = astring::empty_string();
340   to_fill.reset();
341
342   filename_tree *tof = goto_current(scanning);
343   if (!tof) return false;
344
345   // fill in what they wanted.
346   dir_name = tof->_dirname;
347   tof->_files.fill(to_fill);
348
349   return true;
350 }
351
352 bool directory_tree::current(dir_tree_iterator &scanning,
353     filename &dir_name, filename_list &to_fill)
354 {
355   // clear any existing junk.
356   dir_name = astring::empty_string();
357   to_fill.reset();
358
359   filename_tree *tof = goto_current(scanning);
360   if (!tof) return false;
361
362   // fill in what they wanted.
363   dir_name = tof->_dirname;
364   to_fill = tof->_files;
365
366   return true;
367 }
368
369 filename_list *directory_tree::access(dir_tree_iterator &scanning)
370 {
371   filename_tree *tof = goto_current(scanning);
372   if (!tof) return NIL;
373   return &tof->_files;
374 }
375
376 bool directory_tree::depth(dir_tree_iterator &scanning, int &depth)
377 {
378   depth = -1;  // invalid as default.
379   filename_tree *tof = goto_current(scanning);
380   if (!tof) return false;
381   depth = tof->_depth;
382   return true;
383 }
384
385 bool directory_tree::children(dir_tree_iterator &scanning, int &kids)
386 {
387   kids = -1;  // invalid as default.
388   filename_tree *tof = goto_current(scanning);
389   if (!tof) return false;
390   kids = tof->branches();
391   return true;
392 }
393
394 bool directory_tree::next(dir_tree_iterator &scanning)
395 {
396   scanning._current = (filename_tree *)scanning.next();
397   return !!scanning._current;
398 }
399
400 void directory_tree::throw_out(dir_tree_iterator * &to_whack)
401 {
402   WHACK(to_whack);
403 }
404
405 filename_tree *directory_tree::seek(const astring &dir_name_in,
406     bool ignore_initial) const
407 {
408   FUNCDEF("seek");
409   array<filename_tree *> examining;
410     // the list of nodes we're currently looking at.
411
412 #ifdef DEBUG_DIRECTORY_TREE
413   LOG(astring("seeking on root of: ") + *_path);
414 #endif
415
416   astring dir_name = filename(dir_name_in).raw();
417   // set the search path up to have the proper prefix.
418   if (ignore_initial)
419     dir_name = path() + filename::default_separator()
420        + filename(dir_name_in).raw();
421
422 #ifdef DEBUG_DIRECTORY_TREE
423   LOG(astring("adding root: ") + _real_tree->_dirname);
424 #endif
425   examining += _real_tree;
426
427   astring sequel;  // holds extra pieces from filename comparisons.
428
429   // chew on the list of nodes to examine until we run out.
430   while (examining.length()) {
431     int posn;
432     bool found = false;
433     // start looking at all the items in the list, even though we might have
434     // to abandon the iteration if we find a match.
435     filename_tree *check = NIL;
436     for (posn = 0; posn < examining.length(); posn++) {
437       check = examining[posn];
438       filename current(check->_dirname);
439       if (!current.is_normal()) {
440 //#ifdef DEBUG_DIRECTORY_TREE
441         LOG(astring("skipping abnormal dir: \"") + current + "\"");
442 //#endif
443         continue;
444       }
445 #ifdef DEBUG_DIRECTORY_TREE
446       LOG(astring("looking at ") + current.raw());
447 #endif
448       if (current.compare_prefix(dir_name, sequel)) {
449         // we have a match!
450 #ifdef DEBUG_DIRECTORY_TREE
451         LOG(astring("matched! at ") + current.raw());
452 #endif
453         found = true;
454         if (!sequel) {
455           // whoa!  an exact match.  we're done now.
456 #ifdef DEBUG_DIRECTORY_TREE
457           LOG(astring("exact match at ") + current.raw() + "!  done!!!");
458 #endif
459           return check;
460         } else {
461 #ifdef DEBUG_DIRECTORY_TREE
462           LOG(astring("inexact match because sequel=") + sequel);
463 #endif
464         }
465         break;
466       }
467     }
468     if (!found) return NIL;  // we found nothing comparable.
469
470     // we found a partial match.  that means we should start looking at this
471     // node's children for the exact match.
472     if (!check) {
473       // this is a serious logical error!
474       LOG("serious logical error: tree was not located.");
475       return NIL;
476     }
477     examining.reset();  // clear the existing nodes.
478     for (int i = 0; i < check->branches(); i++)
479       examining += (filename_tree *)check->branch(i);
480   }
481
482   return NIL;  // we found nothing that looked like that node.
483 }
484
485 bool directory_tree::calculate(bool just_size)
486 { return calculate(_real_tree, just_size); }
487
488 bool directory_tree::calculate(filename_tree *start, bool just_size)
489 {
490   FUNCDEF("calculate");
491   dir_tree_iterator *ted = start_at(start, directory_tree::postfix);
492     // create our iterator to do a postfix traversal.  why postfix?  well,
493     // prefix has been used elsewhere and since it doesn't really matter what
494     // order we visit the nodes here, it's good to change up.
495
496   int depth;  // current depth in tree.
497   filename curr;  // the current path the iterator is at.
498   filename_list *files;  // the filenames held at the iterator.
499
500   while (directory_tree::current_dir(*ted, curr)) {
501     if (!curr.is_normal()) {
502 //#ifdef DEBUG_DIRECTORY_TREE
503       LOG(astring("skipping abnormal dir: \"") + curr + "\"");
504 //#endif
505       directory_tree::next(*ted);
506       continue;  // scary non-simple file type.
507     }
508     // we have a good directory to show.
509 #ifdef DEBUG_DIRECTORY_TREE
510     LOG(astring("calcing node ") + curr.raw());
511 #endif
512     files = directory_tree::access(*ted);
513     directory_tree::depth(*ted, depth);
514     for (int i = 0; i < files->elements(); i++) {
515       filename curr_file = curr + "/" + *files->borrow(i);
516 #ifdef DEBUG_DIRECTORY_TREE
517       LOG(astring("got a curr file: ") + curr_file);
518 #endif
519       if (!curr_file.is_normal()) {
520 //#ifdef DEBUG_DIRECTORY_TREE
521         LOG(astring("skipping abnormal file: \"") + curr + "\"");
522 //#endif
523         continue;
524       }
525       if (!files->borrow(i)->calculate(curr.raw(), just_size)) {
526         LOG(astring("failure to calculate ") + files->get(i)->text_form());
527       }
528     }
529
530     directory_tree::next(*ted);
531   }
532
533   directory_tree::throw_out(ted);
534   return true;
535 }
536
537 bool directory_tree::compare_trees(const directory_tree &source,
538     const directory_tree &target, filename_list &differences,
539     file_info::file_similarity how_to_compare)
540 {
541   return compare_trees(source, astring::empty_string(), target,
542       astring::empty_string(), differences, how_to_compare);
543 }
544
545 bool directory_tree::compare_trees(const directory_tree &source,
546     const astring &source_start_in, const directory_tree &target,
547     const astring &target_start_in, filename_list &differences,
548     file_info::file_similarity how_compare)
549 {
550   FUNCDEF("compare_trees");
551   differences.reset();  // prepare it for storage.
552
553   // make sure we get canonical names to work with.
554   filename source_start(source_start_in);
555   filename target_start(target_start_in);
556
557   dir_tree_iterator *ted = source.start(directory_tree::prefix);
558     // create our iterator to do a prefix traversal.
559
560   astring real_source_start = source.path();
561   if (source_start.raw().t()) {
562     // move to the right place.
563     real_source_start = real_source_start + filename::default_separator()
564         + source_start.raw();
565     if (!directory_tree::jump_to(*ted, source_start.raw())) {
566       // can't even start comparing.
567       LOG(astring("failed to find source start in tree, given as ")
568           + source_start.raw());
569       return false;
570     }
571   }
572
573   filename curr;  // the current path the iterator is at.
574   filename_list files;  // the filenames held at the iterator.
575
576   // calculate where our comparison point is on the source.
577   int source_pieces = 0;
578   {
579     string_array temp;
580     filename(real_source_start).separate(temp);
581     source_pieces = temp.length();
582   }
583
584   bool seen_zero_pieces = false;
585   while (directory_tree::current(*ted, curr, files)) {
586     // we're in a place in the source tree now.  let's compare it with the
587     // target's recollection.
588
589 #ifdef DEBUG_DIRECTORY_TREE
590     LOG(astring("curr dir in tree: ") + curr.raw());
591 #endif
592
593     string_array pieces;
594     curr.separate(pieces);  // get the components of the current location.
595 #ifdef DEBUG_DIRECTORY_TREE
596     LOG(astring("name in pieces:") + pieces.text_form());
597 #endif
598     pieces.zap(0, source_pieces - 1);
599       // snap the root components out of there.
600
601     filename corresponding_name;
602     corresponding_name.join(pieces);
603 #ifdef DEBUG_DIRECTORY_TREE
604     LOG(astring("computed target name as: ") + corresponding_name);
605 #endif
606     filename original_correspondence(corresponding_name);
607
608     if (!corresponding_name.raw().t()) {
609       if (seen_zero_pieces) {
610 #ifdef DEBUG_DIRECTORY_TREE
611         LOG(astring("breaking out now due to empty correspondence"));
612 #endif
613         break;
614       }
615       seen_zero_pieces = true;
616     }
617     if (target_start.raw().t()) {
618       corresponding_name = filename(target_start.raw()
619           + filename::default_separator() + corresponding_name.raw());
620     }
621 #ifdef DEBUG_DIRECTORY_TREE
622     LOG(astring("target with start is: ") + corresponding_name);
623 #endif
624
625     filename_tree *target_now = target.seek(corresponding_name.raw(), true);
626     if (!target_now) {
627       // that entire sub-tree is missing.  add all of the files here into
628       // the list.
629 #ifdef DEBUG_DIRECTORY_TREE
630       LOG(astring("could not find dir in target for ") + curr.raw()
631           + " which we computed corresp as " + corresponding_name.raw());
632 #endif
633     }
634
635     // now scan across all the files that are in our source list.
636     for (int i = 0; i < files.elements(); i++) {
637       if (!target_now  // there was no node, so we're adding everything...
638           || !target_now->_files.member_with_state(*files[i], how_compare) ) {
639         // ... or we need to add this file since it's missing.
640 #ifdef DEBUG_DIRECTORY_TREE
641         LOG(astring("adding record: ") + files[i]->text_form());
642 #endif
643
644         file_info *new_record = new file_info(*files[i]);
645         // record the file time for use later in saving.
646         new_record->calculate(curr, true);
647         astring original = new_record->raw();
648 #ifdef DEBUG_DIRECTORY_TREE
649         LOG(astring("current: ") + new_record->raw());
650 #endif
651
652         astring actual_name = source_start.raw();
653 #ifdef DEBUG_DIRECTORY_TREE
654         if (actual_name.t()) LOG(astring("sname=") + actual_name);
655 #endif
656         if (actual_name.length()) actual_name += filename::default_separator();
657         actual_name += original_correspondence.raw();
658         if (actual_name.length()) actual_name += filename::default_separator();
659         actual_name += new_record->raw();
660 #ifdef DEBUG_DIRECTORY_TREE
661         if (actual_name.t()) LOG(astring("sname=") + actual_name);
662 #endif
663         (filename &)(*new_record) = filename(actual_name);
664
665         astring targ_name = corresponding_name.raw();
666 #ifdef DEBUG_DIRECTORY_TREE
667         if (targ_name.t()) LOG(astring("tname=") + targ_name);
668 #endif
669         if (targ_name.length()) targ_name += filename::default_separator();
670         targ_name += original;
671 #ifdef DEBUG_DIRECTORY_TREE
672         if (targ_name.t()) LOG(astring("tname=") + targ_name);
673 #endif
674
675         new_record->secondary(targ_name);
676
677         differences += new_record;
678 #ifdef DEBUG_DIRECTORY_TREE
679         LOG(astring("came out as: ") + new_record->text_form());
680 #endif
681       }
682     }
683     
684     // go to the next place.
685     directory_tree::next(*ted);
686   }
687
688   directory_tree::throw_out(ted);
689
690   return true;
691 }
692
693 outcome directory_tree::find_common_root(const astring &finding, bool exists,
694     filename_tree * &found, astring &reassembled, string_array &pieces,
695     int &match_place)
696 {
697   FUNCDEF("find_common_root");
698   // test the path to find what it is.
699   filename adding(finding);
700   if (exists && !adding.good())
701     return common::BAD_INPUT;  // not a good path.
702   int file_subtract = 0;  // if it's a file, then we remove last component.
703   if (exists && !adding.is_directory()) file_subtract = 1;
704
705   // break up the path into pieces.
706   pieces.reset();
707   adding.separate(pieces);
708
709   // break up our root into pieces; we must take off components that are
710   // already in the root.
711   string_array root_pieces;
712   filename temp_file(path());
713   temp_file.separate(root_pieces);
714
715   // locate the last place where the path we were given touches our tree.
716   // it could be totally new, partially new, or already contained.
717   filename_tree *last_match = _real_tree;  // where the common root is located.
718   int list_length = pieces.length() - file_subtract;
719   reassembled = "";
720
721   // we must put all the pieces in that already come from the root.
722   for (int i = 0; i < root_pieces.length() - 1; i++) {
723     bool add_slash = false;
724     if (reassembled.length() && (reassembled[reassembled.end()] != '/') )
725       add_slash = true;
726     if (add_slash) reassembled += "/";
727     reassembled += pieces[i];
728     if (reassembled[reassembled.end()] == ':') {
729 #ifdef DEBUG_DIRECTORY_TREE
730       LOG(astring("skipping drive component ") + reassembled);
731 #endif
732       continue;
733     }
734   }
735
736 #ifdef DEBUG_DIRECTORY_TREE
737   LOG(astring("after pre-assembly, path is ") + reassembled);
738 #endif
739
740   outcome to_return = common::NOT_FOUND;
741
742   for (match_place = root_pieces.length() - 1; match_place < list_length;
743       match_place++) {
744     // add a slash if there's not one present already.
745     bool add_slash = false;
746     if (reassembled.length() && (reassembled[reassembled.end()] != '/') )
747       add_slash = true;
748     // add the next component in to our path.
749     if (add_slash) reassembled += "/";
750     reassembled += pieces[match_place];
751     // special case for dos paths.
752     if (reassembled[reassembled.end()] == ':') {
753 #ifdef DEBUG_DIRECTORY_TREE
754       LOG(astring("skipping drive component ") + reassembled);
755 #endif
756       continue;
757     }
758     reassembled = filename(reassembled).raw();  // force compliance with OS.
759 #ifdef DEBUG_DIRECTORY_TREE
760     LOG(astring("now seeking ") + reassembled);
761 #endif
762     filename_tree *sought = seek(reassembled, false);
763     if (!sought) {
764 #ifdef DEBUG_DIRECTORY_TREE
765       LOG(astring("couldn't find ") + reassembled);
766 #endif
767       if (!exists && (match_place == list_length - 1)) {
768         // see if we can get a match on a file rather than a directory, but
769         // only if we're near the end of the compare.
770         if (last_match->_files.member(pieces[match_place])) {
771           // aha!  a file match.
772           to_return = common::OKAY;
773           match_place--;
774           break;
775         }
776       }
777       match_place--;
778       break;
779     } else {
780       // record where we last had some success.
781 #ifdef DEBUG_DIRECTORY_TREE
782       LOG(astring("found subtree for ") + reassembled);
783 #endif
784       last_match = sought;
785     }
786   }
787   // this is a success, but our loop structure can put us one past the right
788   // place.
789   if (match_place >= list_length) {
790     match_place = list_length - 1;
791     to_return = common::OKAY;
792   }
793
794   found = last_match;
795   return to_return;
796 }
797
798 outcome directory_tree::add_path(const astring &new_item, bool just_size)
799 {
800   FUNCDEF("add_path");
801   // test the path to find out what it is.
802   filename adding(new_item);
803   if (!adding.good()) {
804     LOG(astring("non-existent new item!  ") + new_item);
805     return common::NOT_FOUND;  // not an existing path.
806   }
807   if (!adding.is_normal()) {
808 //#ifdef DEBUG_DIRECTORY_TREE
809     LOG(astring("abnormal new item:  ") + new_item);
810 //#endif
811     return common::BAD_INPUT;  // not a good path.
812   }
813   int file_subtract = 0;  // if it's a file, then we remove last component.
814   if (!adding.is_directory()) file_subtract = 1;
815 #ifdef DEBUG_DIRECTORY_TREE
816   if (file_subtract) { LOG(astring("adding a file ") + new_item); }
817   else { LOG(astring("adding a directory ") + new_item); }
818 #endif
819
820   // find the common root, break up the path into pieces, and tell us where
821   // we matched.
822   string_array pieces;
823   filename_tree *last_match = NIL;
824   int comp_index;
825   astring reassembled;  // this will hold the common root.
826   outcome ret = find_common_root(new_item, true, last_match, reassembled,
827       pieces, comp_index);
828   if (!last_match) {
829     LOG(astring("serious error finding common root for ") + new_item
830         + ", got NIL tree.");
831     return common::FAILURE;  // something serious isn't right.
832   }
833
834   if (!file_subtract) {
835     if (ret != common::OKAY) {
836       // if it's a new directory, we add a new node for traverse to work on.
837 #ifdef DEBUG_DIRECTORY_TREE
838       LOG(astring("now adding node for ") + reassembled);
839 #endif
840       filename_tree *new_branch = new filename_tree;
841       new_branch->_depth = last_match->_depth + 1;
842       last_match->attach(new_branch);
843       last_match = new_branch;
844     } else {
845 #ifdef DEBUG_DIRECTORY_TREE
846       LOG(astring("matched properly.  reassembled set to ") + reassembled);
847 #endif
848     }
849   }
850
851   if (file_subtract) {
852     if (ret != common::OKAY) {
853 #ifdef DEBUG_DIRECTORY_TREE
854       LOG(astring("common gave us posn of: ") + reassembled);
855 #endif
856       // handle the case for files now that we have our proper node.
857       string_array partial_pieces;
858       filename(reassembled).separate(partial_pieces);
859       int levels_missing = pieces.length() - partial_pieces.length();
860
861       // we loop over all the pieces that were missing in between the last
862       // common root and the file's final location.
863       for (int i = 0; i < levels_missing; i++) {
864 #ifdef DEBUG_DIRECTORY_TREE
865         LOG(astring("adding intermediate directory: ") + reassembled);
866 #endif
867         filename_tree *new_branch = new filename_tree;
868         new_branch->_depth = last_match->_depth + 1;
869         new_branch->_dirname = filename(reassembled).raw();
870         last_match->attach(new_branch);
871         last_match = new_branch;
872         reassembled += astring("/") + pieces[partial_pieces.length() + i];
873         reassembled = filename(reassembled).raw();  // canonicalize.
874       }
875     }
876
877     if (!last_match->_files.find(pieces[pieces.last()])) {
878 #ifdef DEBUG_DIRECTORY_TREE
879       LOG(astring("adding new file ") + pieces[pieces.last()]
880         + " at " + reassembled);
881 #endif
882       file_info *to_add = new file_info(pieces[pieces.last()], 0);
883       to_add->calculate(reassembled, just_size);
884       last_match->_files += to_add;
885     } else {
886 #ifdef DEBUG_DIRECTORY_TREE
887       LOG(astring("not adding existing file ") + pieces[pieces.last()]
888           + " at " + reassembled);
889 #endif
890     }
891   } else {
892     // handle the case for directories.
893 #ifdef DEBUG_DIRECTORY_TREE
894     LOG(astring("doing traverse in ") + last_match->_dirname
895         + " to add " + reassembled);
896 #endif
897     traverse(reassembled, "*", *last_match);
898 //hmmm: maybe provide pattern capability instead of assuming all files.
899     calculate(last_match, just_size);
900   }
901
902   return common::OKAY;
903 }
904
905 outcome directory_tree::remove_path(const astring &zap_item)
906 {
907   FUNCDEF("remove_path");
908   // find the common root, if one exists.  if not, we're not going to do this.
909   string_array pieces;
910   filename_tree *last_match = NIL;
911   int comp_index;
912   astring reassembled;
913   outcome ret = find_common_root(zap_item, false, last_match, reassembled,
914       pieces, comp_index);
915   if (!last_match) return common::NOT_FOUND;
916   // if we didn't actually finish iterating to the file, then we're not
917   // whacking anything.
918   if (ret != common::OKAY) {
919 #ifdef DEBUG_DIRECTORY_TREE
920     LOG(astring("got error seeking ") + zap_item + " of "
921         + common::outcome_name(ret));
922 #endif
923     return ret;
924   }
925
926   if (comp_index == pieces.last()) {
927     // if the names match fully, then we're talking about a directory.
928 #ifdef DEBUG_DIRECTORY_TREE
929     LOG(astring("found directory match for ") + zap_item);
930 #endif
931   } else {
932 #ifdef DEBUG_DIRECTORY_TREE
933     LOG(astring("may have found file match for ") + zap_item);
934 #endif
935     filename to_seek(pieces[pieces.last()]);
936     if (!last_match->_files.member(to_seek)) {
937       // this file is not a member, so we must say it's not found.
938 #ifdef DEBUG_DIRECTORY_TREE
939       LOG(astring("couldn't find file match in common root for ") + zap_item);
940 #endif
941       return common::NOT_FOUND;
942     } else {
943       int indy = last_match->_files.locate(to_seek);
944 #ifdef DEBUG_DIRECTORY_TREE
945       LOG(astring("found match to remove for ") + zap_item);
946 #endif
947       last_match->_files.zap(indy, indy);
948       return common::OKAY;  // done!
949     }
950   }
951
952 #ifdef DEBUG_DIRECTORY_TREE
953   LOG(astring("going to whack node at: ") + last_match->_dirname.raw());
954 #endif
955
956   // we're whacking directories, so we need to take out last_match and below.
957   filename_tree *parent = (filename_tree *)last_match->parent();
958   if (!parent || (last_match == _real_tree)) {
959     // this seems to be matching the whole tree.  we disallow that.
960 #ifdef DEBUG_DIRECTORY_TREE
961     LOG("there's a problem whacking this node; it's the root.");
962 #endif
963     return common::BAD_INPUT;
964   }
965 #ifdef DEBUG_DIRECTORY_TREE
966   LOG(astring("pruning tree at ") + last_match->_dirname.raw());
967 #endif
968   parent->prune(last_match);
969   WHACK(last_match);
970
971   return common::OKAY;
972 }
973
974 } //namespace.
975
976