noisy logging turned on to help look for bug in directory tree.
[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 <structures/object_packers.h>
24 #include <structures/string_array.h>
25 #include <textual/parser_bits.h>
26 #include <textual/string_manipulation.h>
27
28 #include <stdio.h>
29
30 using namespace basis;
31 using namespace structures;
32 using namespace nodes;
33 using namespace textual;
34
35 #define DEBUG_DIRECTORY_TREE
36   // uncomment for noisier version.
37
38 #undef LOG
39 #define LOG(to_print) printf("%s::%s: %s\n", static_class_name(), func, astring(to_print).s())
40 //CLASS_EMERGENCY_LOG(program_wide_logger::get(), s)
41
42 //////////////
43
44 namespace filesystem {
45
46 class dir_tree_iterator : public filename_tree::iterator
47 {
48 public:
49   filename_tree *_current;
50
51   dir_tree_iterator(const filename_tree *initial,
52       tree::traversal_directions dir)
53   : filename_tree::iterator(initial, dir), _current(NIL) {}
54 };
55
56 //////////////
57
58 directory_tree::directory_tree()
59 : _scanned_okay(false),
60   _path(new astring),
61   _pattern(new astring),
62   _real_tree(new filename_tree),
63   _ignore_files(false),
64   _creator(new fname_tree_creator)
65 {
66 }
67
68 directory_tree::directory_tree(const astring &path, const char *pattern,
69     bool ignore_files)
70 : _scanned_okay(false),
71   _path(new astring(path)),
72   _pattern(new astring(pattern)),
73   _real_tree(NIL),
74   _ignore_files(ignore_files),
75   _creator(new fname_tree_creator)
76 {
77   reset(path, pattern);
78 }
79
80 directory_tree::~directory_tree()
81 {
82   _scanned_okay = false;
83   WHACK(_path);
84   WHACK(_pattern);
85   WHACK(_real_tree);
86   WHACK(_creator);
87 }
88
89 const astring &directory_tree::path() const { return *_path; }
90
91 int directory_tree::packed_size() const
92 {
93   return 2 * PACKED_SIZE_INT32
94       + _path->packed_size()
95       + _pattern->packed_size()
96       + _real_tree->recursive_packed_size();
97 }
98
99 void directory_tree::pack(byte_array &packed_form) const
100 {
101   attach(packed_form, int(_scanned_okay));
102   attach(packed_form, int(_ignore_files));
103   _path->pack(packed_form);
104   _pattern->pack(packed_form);
105   _real_tree->recursive_pack(packed_form);
106 }
107
108 bool directory_tree::unpack(byte_array &packed_form)
109 {
110   int temp;
111   if (!detach(packed_form, temp)) return false;
112   _scanned_okay = temp;
113   if (!detach(packed_form, temp)) return false;
114   _ignore_files = temp;
115   if (!_path->unpack(packed_form)) return false;
116   if (!_pattern->unpack(packed_form)) return false;
117   WHACK(_real_tree);
118   _real_tree = (filename_tree *)packable_tree::recursive_unpack
119       (packed_form, *_creator);
120   if (!_real_tree) {
121     _real_tree = new filename_tree;  // reset it.
122     return false;
123   }
124   return true;
125 }
126
127 void directory_tree::text_form(astring &target, bool show_files)
128 {
129   dir_tree_iterator *ted = start(directory_tree::prefix);
130     // create our iterator to do a prefix traversal.
131
132   int depth;  // current depth in tree.
133   filename curr;  // the current path the iterator is at.
134   string_array files;  // the filenames held at the iterator.
135
136   while (current(*ted, curr, files)) {
137     // we have a good directory to show.
138     directory_tree::depth(*ted, depth);
139     target += string_manipulation::indentation(depth * 2) + astring("[")
140         + curr.raw() + "]" + parser_bits::platform_eol_to_chars();
141     if (show_files) {
142       astring names;
143       for (int i = 0; i < files.length(); i++) names += files[i] + " ";
144       if (names.length()) {
145         astring split;
146         string_manipulation::split_lines(names, split, depth * 2 + 2);
147         target += split + parser_bits::platform_eol_to_chars();
148       }
149     }
150
151     // go to the next place.
152     next(*ted);
153   }
154
155   throw_out(ted);
156 }
157
158 void directory_tree::traverse(const astring &path, const char *pattern,
159     filename_tree &add_to)
160 {
161 #ifdef DEBUG_DIRECTORY_TREE
162   FUNCDEF("traverse");
163 #endif
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.raw());
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 LOG(astring("bailing on weird dir: ") + new_path);
192       continue;  // only regular directories please.
193     }
194     for (int q = 0; q < add_to.branches(); q++) {
195       filename_tree *curr_kid = (filename_tree *)add_to.branch(q);
196 #ifdef DEBUG_DIRECTORY_TREE
197       LOG(astring("curr kid: ") + curr_kid->_dirname);
198 #endif
199       if (filename(new_path).raw().iequals(filename
200           (curr_kid->_dirname).raw())) {
201         new_branch = curr_kid;
202 #ifdef DEBUG_DIRECTORY_TREE
203         LOG(astring("using existing branch for ") + new_path);
204 #endif
205         break;
206       }
207     }
208     if (!new_branch) {
209 #ifdef DEBUG_DIRECTORY_TREE
210       LOG(astring("adding new branch for ") + new_path);
211 #endif
212       new_branch = new filename_tree;
213       add_to.attach(new_branch);
214       new_branch->_depth = add_to._depth + 1;
215     }
216 #ifdef DEBUG_DIRECTORY_TREE
217     LOG(astring("traversing sub-node ") + new_path);
218 #endif
219     traverse(new_path, pattern, *new_branch);
220   }
221 }
222
223 bool directory_tree::reset(const astring &path, const char *pattern)
224 {
225   _scanned_okay = false;
226   WHACK(_real_tree);
227   *_path = path;
228   *_pattern = pattern;
229   _real_tree = new filename_tree;
230
231   // check that the top-level is healthy.
232   directory curr(path, "*");
233   if (!curr.good()) return false;
234     // our only exit condition; other directories might not be accessible
235     // underneath, but the top one must be accessible for us to even start
236     // the scanning.
237
238   traverse(path, pattern, *_real_tree);
239   _scanned_okay = true;;
240   return true;
241 }
242
243 dir_tree_iterator *directory_tree::start_at(filename_tree *start,
244     traversal_types type) const
245 {
246   // translate to the lower level traversal enum.
247   tree::traversal_directions dir = tree::prefix;
248   if (type == infix) dir = tree::infix;
249   else if (type == postfix) dir = tree::postfix;
250
251   return new dir_tree_iterator(start, dir);
252 }
253
254 dir_tree_iterator *directory_tree::start(traversal_types type) const
255 {
256   // translate to the lower level traversal enum.
257   tree::traversal_directions dir = tree::prefix;
258   if (type == infix) dir = tree::infix;
259   else if (type == postfix) dir = tree::postfix;
260
261   return new dir_tree_iterator(_real_tree, dir);
262 }
263
264 bool directory_tree::jump_to(dir_tree_iterator &scanning,
265     const astring &sub_path)
266 {
267 #ifdef DEBUG_DIRECTORY_TREE
268   FUNCDEF("jump_to");
269 #endif
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 #ifdef DEBUG_DIRECTORY_TREE
440       LOG(astring("looking at ") + current.raw());
441 #endif
442       if (current.compare_prefix(dir_name, sequel)) {
443         // we have a match!
444 #ifdef DEBUG_DIRECTORY_TREE
445         LOG(astring("matched! at ") + current.raw());
446 #endif
447         found = true;
448         if (!sequel) {
449           // whoa!  an exact match.  we're done now.
450 #ifdef DEBUG_DIRECTORY_TREE
451           LOG(astring("exact match at ") + current.raw() + "!  done!!!");
452 #endif
453           return check;
454         } else {
455 #ifdef DEBUG_DIRECTORY_TREE
456           LOG(astring("inexact match because sequel=") + sequel);
457 #endif
458         }
459         break;
460       }
461     }
462     if (!found) return NIL;  // we found nothing comparable.
463
464     // we found a partial match.  that means we should start looking at this
465     // node's children for the exact match.
466     if (!check) {
467       // this is a serious logical error!
468       LOG("serious logical error: tree was not located.");
469       return NIL;
470     }
471     examining.reset();  // clear the existing nodes.
472     for (int i = 0; i < check->branches(); i++)
473       examining += (filename_tree *)check->branch(i);
474   }
475
476   return NIL;  // we found nothing that looked like that node.
477 }
478
479 bool directory_tree::calculate(bool just_size)
480 { return calculate(_real_tree, just_size); }
481
482 bool directory_tree::calculate(filename_tree *start, bool just_size)
483 {
484   FUNCDEF("calculate");
485   dir_tree_iterator *ted = start_at(start, directory_tree::postfix);
486     // create our iterator to do a postfix traversal.  why postfix?  well,
487     // prefix has been used elsewhere and since it doesn't really matter what
488     // order we visit the nodes here, it's good to change up.
489
490   int depth;  // current depth in tree.
491   filename curr;  // the current path the iterator is at.
492   filename_list *files;  // the filenames held at the iterator.
493
494   while (directory_tree::current_dir(*ted, curr)) {
495     // we have a good directory to show.
496 #ifdef DEBUG_DIRECTORY_TREE
497     LOG(astring("calcing node ") + curr.raw());
498 #endif
499     files = directory_tree::access(*ted);
500     directory_tree::depth(*ted, depth);
501     for (int i = 0; i < files->elements(); i++) {
502       if (!files->borrow(i)->calculate(curr.raw(), just_size)) {
503         LOG(astring("failure to calculate ") + files->get(i)->text_form());
504       }
505     }
506
507     directory_tree::next(*ted);
508   }
509
510   directory_tree::throw_out(ted);
511   return true;
512 }
513
514 bool directory_tree::compare_trees(const directory_tree &source,
515     const directory_tree &target, filename_list &differences,
516     file_info::file_similarity how_to_compare)
517 {
518   return compare_trees(source, astring::empty_string(), target,
519       astring::empty_string(), differences, how_to_compare);
520 }
521
522 bool directory_tree::compare_trees(const directory_tree &source,
523     const astring &source_start_in, const directory_tree &target,
524     const astring &target_start_in, filename_list &differences,
525     file_info::file_similarity how_compare)
526 {
527   FUNCDEF("compare_trees");
528   differences.reset();  // prepare it for storage.
529
530   // make sure we get canonical names to work with.
531   filename source_start(source_start_in);
532   filename target_start(target_start_in);
533
534   dir_tree_iterator *ted = source.start(directory_tree::prefix);
535     // create our iterator to do a prefix traversal.
536
537   astring real_source_start = source.path();
538   if (source_start.raw().t()) {
539     // move to the right place.
540     real_source_start = real_source_start + filename::default_separator()
541         + source_start.raw();
542     if (!directory_tree::jump_to(*ted, source_start.raw())) {
543       // can't even start comparing.
544       LOG(astring("failed to find source start in tree, given as ")
545           + source_start.raw());
546       return false;
547     }
548   }
549
550   filename curr;  // the current path the iterator is at.
551   filename_list files;  // the filenames held at the iterator.
552
553   // calculate where our comparison point is on the source.
554   int source_pieces = 0;
555   {
556     string_array temp;
557     filename(real_source_start).separate(temp);
558     source_pieces = temp.length();
559   }
560
561   bool seen_zero_pieces = false;
562   while (directory_tree::current(*ted, curr, files)) {
563     // we're in a place in the source tree now.  let's compare it with the
564     // target's recollection.
565
566 #ifdef DEBUG_DIRECTORY_TREE
567     LOG(astring("curr dir in tree: ") + curr.raw());
568 #endif
569
570     string_array pieces;
571     curr.separate(pieces);  // get the components of the current location.
572 #ifdef DEBUG_DIRECTORY_TREE
573     LOG(astring("name in pieces:") + pieces.text_form());
574 #endif
575     pieces.zap(0, source_pieces - 1);
576       // snap the root components out of there.
577
578     filename corresponding_name;
579     corresponding_name.join(pieces);
580 #ifdef DEBUG_DIRECTORY_TREE
581     LOG(astring("computed target name as: ") + corresponding_name);
582 #endif
583     filename original_correspondence(corresponding_name);
584
585     if (!corresponding_name.raw().t()) {
586       if (seen_zero_pieces) {
587 #ifdef DEBUG_DIRECTORY_TREE
588         LOG(astring("breaking out now due to empty correspondence"));
589 #endif
590         break;
591       }
592       seen_zero_pieces = true;
593     }
594     if (target_start.raw().t()) {
595       corresponding_name = filename(target_start.raw()
596           + filename::default_separator() + corresponding_name.raw());
597     }
598 #ifdef DEBUG_DIRECTORY_TREE
599     LOG(astring("target with start is: ") + corresponding_name);
600 #endif
601
602     filename_tree *target_now = target.seek(corresponding_name.raw(), true);
603     if (!target_now) {
604       // that entire sub-tree is missing.  add all of the files here into
605       // the list.
606 #ifdef DEBUG_DIRECTORY_TREE
607       LOG(astring("could not find dir in target for ") + curr.raw()
608           + " which we computed corresp as " + corresponding_name.raw());
609 #endif
610     }
611
612     // now scan across all the files that are in our source list.
613     for (int i = 0; i < files.elements(); i++) {
614       if (!target_now  // there was no node, so we're adding everything...
615           || !target_now->_files.member_with_state(*files[i], how_compare) ) {
616         // ... or we need to add this file since it's missing.
617 /*
618 //hmmm: this one might be redundant.  we shouldn't add it in the first place.
619         if (!files[i]->is_normal()) {
620           LOG(astring("skipping abnormal file:  ") + *files[i]);
621           continue;  // wasn't useful to do this one.
622         }
623 */
624 #ifdef DEBUG_DIRECTORY_TREE
625         LOG(astring("adding record: ") + files[i]->text_form());
626 #endif
627
628         file_info *new_record = new file_info(*files[i]);
629         // record the file time for use later in saving.
630         new_record->calculate(curr, true);
631         astring original = new_record->raw();
632 #ifdef DEBUG_DIRECTORY_TREE
633         LOG(astring("current: ") + new_record->raw());
634 #endif
635
636         astring actual_name = source_start.raw();
637 #ifdef DEBUG_DIRECTORY_TREE
638         if (actual_name.t()) LOG(astring("sname=") + actual_name);
639 #endif
640         if (actual_name.length()) actual_name += filename::default_separator();
641         actual_name += original_correspondence.raw();
642         if (actual_name.length()) actual_name += filename::default_separator();
643         actual_name += new_record->raw();
644 #ifdef DEBUG_DIRECTORY_TREE
645         if (actual_name.t()) LOG(astring("sname=") + actual_name);
646 #endif
647         (filename &)(*new_record) = filename(actual_name);
648
649         astring targ_name = corresponding_name.raw();
650 #ifdef DEBUG_DIRECTORY_TREE
651         if (targ_name.t()) LOG(astring("tname=") + targ_name);
652 #endif
653         if (targ_name.length()) targ_name += filename::default_separator();
654         targ_name += original;
655 #ifdef DEBUG_DIRECTORY_TREE
656         if (targ_name.t()) LOG(astring("tname=") + targ_name);
657 #endif
658
659         new_record->secondary(targ_name);
660
661         differences += new_record;
662 #ifdef DEBUG_DIRECTORY_TREE
663         LOG(astring("came out as: ") + new_record->text_form());
664 #endif
665       }
666     }
667     
668     // go to the next place.
669     directory_tree::next(*ted);
670   }
671
672   directory_tree::throw_out(ted);
673
674   return true;
675 }
676
677 outcome directory_tree::find_common_root(const astring &finding, bool exists,
678     filename_tree * &found, astring &reassembled, string_array &pieces,
679     int &match_place)
680 {
681 #ifdef DEBUG_DIRECTORY_TREE
682   FUNCDEF("find_common_root");
683 #endif
684   // test the path to find what it is.
685   filename adding(finding);
686   if (exists && !adding.good())
687     return common::BAD_INPUT;  // not a good path.
688   int file_subtract = 0;  // if it's a file, then we remove last component.
689   if (exists && !adding.is_directory()) file_subtract = 1;
690
691   // break up the path into pieces.
692   pieces.reset();
693   adding.separate(pieces);
694
695   // break up our root into pieces; we must take off components that are
696   // already in the root.
697   string_array root_pieces;
698   filename temp_file(path());
699   temp_file.separate(root_pieces);
700
701   // locate the last place where the path we were given touches our tree.
702   // it could be totally new, partially new, or already contained.
703   filename_tree *last_match = _real_tree;  // where the common root is located.
704   int list_length = pieces.length() - file_subtract;
705   reassembled = "";
706
707   // we must put all the pieces in that already come from the root.
708   for (int i = 0; i < root_pieces.length() - 1; i++) {
709     bool add_slash = false;
710     if (reassembled.length() && (reassembled[reassembled.end()] != '/') )
711       add_slash = true;
712     if (add_slash) reassembled += "/";
713     reassembled += pieces[i];
714     if (reassembled[reassembled.end()] == ':') {
715 #ifdef DEBUG_DIRECTORY_TREE
716       LOG(astring("skipping drive component ") + reassembled);
717 #endif
718       continue;
719     }
720   }
721
722 #ifdef DEBUG_DIRECTORY_TREE
723   LOG(astring("after pre-assembly, path is ") + reassembled);
724 #endif
725
726   outcome to_return = common::NOT_FOUND;
727
728   for (match_place = root_pieces.length() - 1; match_place < list_length;
729       match_place++) {
730     // add a slash if there's not one present already.
731     bool add_slash = false;
732     if (reassembled.length() && (reassembled[reassembled.end()] != '/') )
733       add_slash = true;
734     // add the next component in to our path.
735     if (add_slash) reassembled += "/";
736     reassembled += pieces[match_place];
737     // special case for dos paths.
738     if (reassembled[reassembled.end()] == ':') {
739 #ifdef DEBUG_DIRECTORY_TREE
740       LOG(astring("skipping drive component ") + reassembled);
741 #endif
742       continue;
743     }
744     reassembled = filename(reassembled).raw();  // force compliance with OS.
745 #ifdef DEBUG_DIRECTORY_TREE
746     LOG(astring("now seeking ") + reassembled);
747 #endif
748     filename_tree *sought = seek(reassembled, false);
749     if (!sought) {
750 #ifdef DEBUG_DIRECTORY_TREE
751       LOG(astring("couldn't find ") + reassembled);
752 #endif
753       if (!exists && (match_place == list_length - 1)) {
754         // see if we can get a match on a file rather than a directory, but
755         // only if we're near the end of the compare.
756         if (last_match->_files.member(pieces[match_place])) {
757           // aha!  a file match.
758           to_return = common::OKAY;
759           match_place--;
760           break;
761         }
762       }
763       match_place--;
764       break;
765     } else {
766       // record where we last had some success.
767 #ifdef DEBUG_DIRECTORY_TREE
768       LOG(astring("found subtree for ") + reassembled);
769 #endif
770       last_match = sought;
771     }
772   }
773   // this is a success, but our loop structure can put us one past the right
774   // place.
775   if (match_place >= list_length) {
776     match_place = list_length - 1;
777     to_return = common::OKAY;
778   }
779
780   found = last_match;
781   return to_return;
782 }
783
784 outcome directory_tree::add_path(const astring &new_item, bool just_size)
785 {
786   FUNCDEF("add_path");
787   // test the path to find out what it is.
788   filename adding(new_item);
789   if (!adding.good()) {
790     LOG(astring("non-existent new item!  ") + new_item);
791     return common::NOT_FOUND;  // not an existing path.
792   }
793   if (!adding.is_normal()) {
794     LOG(astring("abnormal new item:  ") + new_item);
795     return common::BAD_INPUT;  // not a good path.
796   }
797   int file_subtract = 0;  // if it's a file, then we remove last component.
798   if (!adding.is_directory()) file_subtract = 1;
799 #ifdef DEBUG_DIRECTORY_TREE
800   if (file_subtract) LOG(astring("adding a file ") + new_item);
801   else LOG(astring("adding a directory ") + new_item);
802 #endif
803
804   // find the common root, break up the path into pieces, and tell us where
805   // we matched.
806   string_array pieces;
807   filename_tree *last_match = NIL;
808   int comp_index;
809   astring reassembled;  // this will hold the common root.
810   outcome ret = find_common_root(new_item, true, last_match, reassembled,
811       pieces, comp_index);
812   if (!last_match) {
813     LOG(astring("serious error finding common root for ") + new_item
814         + ", got NIL tree.");
815     return common::FAILURE;  // something serious isn't right.
816   }
817
818   if (!file_subtract) {
819     if (ret != common::OKAY) {
820       // if it's a new directory, we add a new node for traverse to work on.
821 #ifdef DEBUG_DIRECTORY_TREE
822       LOG(astring("now adding node for ") + reassembled);
823 #endif
824       filename_tree *new_branch = new filename_tree;
825       new_branch->_depth = last_match->_depth + 1;
826       last_match->attach(new_branch);
827       last_match = new_branch;
828     } else {
829 #ifdef DEBUG_DIRECTORY_TREE
830       LOG(astring("matched properly.  reassembled set to ") + reassembled);
831 #endif
832     }
833   }
834
835   if (file_subtract) {
836     if (ret != common::OKAY) {
837 #ifdef DEBUG_DIRECTORY_TREE
838       LOG(astring("common gave us posn of: ") + reassembled);
839 #endif
840       // handle the case for files now that we have our proper node.
841       string_array partial_pieces;
842       filename(reassembled).separate(partial_pieces);
843       int levels_missing = pieces.length() - partial_pieces.length();
844
845       // we loop over all the pieces that were missing in between the last
846       // common root and the file's final location.
847       for (int i = 0; i < levels_missing; i++) {
848 #ifdef DEBUG_DIRECTORY_TREE
849         LOG(astring("adding intermediate directory: ") + reassembled);
850 #endif
851         filename_tree *new_branch = new filename_tree;
852         new_branch->_depth = last_match->_depth + 1;
853         new_branch->_dirname = filename(reassembled).raw();
854         last_match->attach(new_branch);
855         last_match = new_branch;
856         reassembled += astring("/") + pieces[partial_pieces.length() + i];
857         reassembled = filename(reassembled).raw();  // canonicalize.
858       }
859     }
860
861     if (!last_match->_files.find(pieces[pieces.last()])) {
862 #ifdef DEBUG_DIRECTORY_TREE
863       LOG(astring("adding new file ") + pieces[pieces.last()]
864         + " at " + reassembled);
865 #endif
866       file_info *to_add = new file_info(pieces[pieces.last()], 0);
867       to_add->calculate(reassembled, just_size);
868       last_match->_files += to_add;
869     } else {
870 #ifdef DEBUG_DIRECTORY_TREE
871       LOG(astring("not adding existing file ") + pieces[pieces.last()]
872           + " at " + reassembled);
873 #endif
874     }
875   } else {
876     // handle the case for directories.
877 #ifdef DEBUG_DIRECTORY_TREE
878     LOG(astring("doing traverse in ") + last_match->_dirname
879         + " to add " + reassembled);
880 #endif
881     traverse(reassembled, "*", *last_match);
882 //hmmm: maybe provide pattern capability instead of assuming all files.
883     calculate(last_match, just_size);
884   }
885
886   return common::OKAY;
887 }
888
889 outcome directory_tree::remove_path(const astring &zap_item)
890 {
891 #ifdef DEBUG_DIRECTORY_TREE
892   FUNCDEF("remove_path");
893 #endif
894   // find the common root, if one exists.  if not, we're not going to do this.
895   string_array pieces;
896   filename_tree *last_match = NIL;
897   int comp_index;
898   astring reassembled;
899   outcome ret = find_common_root(zap_item, false, last_match, reassembled,
900       pieces, comp_index);
901   if (!last_match) return common::NOT_FOUND;
902   // if we didn't actually finish iterating to the file, then we're not
903   // whacking anything.
904   if (ret != common::OKAY) {
905 #ifdef DEBUG_DIRECTORY_TREE
906     LOG(astring("got error seeking ") + zap_item + " of "
907         + common::outcome_name(ret));
908 #endif
909     return ret;
910   }
911
912   if (comp_index == pieces.last()) {
913     // if the names match fully, then we're talking about a directory.
914 #ifdef DEBUG_DIRECTORY_TREE
915     LOG(astring("found directory match for ") + zap_item);
916 #endif
917   } else {
918 #ifdef DEBUG_DIRECTORY_TREE
919     LOG(astring("may have found file match for ") + zap_item);
920 #endif
921     filename to_seek(pieces[pieces.last()]);
922     if (!last_match->_files.member(to_seek)) {
923       // this file is not a member, so we must say it's not found.
924 #ifdef DEBUG_DIRECTORY_TREE
925       LOG(astring("couldn't find file match in common root for ") + zap_item);
926 #endif
927       return common::NOT_FOUND;
928     } else {
929       int indy = last_match->_files.locate(to_seek);
930 #ifdef DEBUG_DIRECTORY_TREE
931       LOG(astring("found match to remove for ") + zap_item);
932 #endif
933       last_match->_files.zap(indy, indy);
934       return common::OKAY;  // done!
935     }
936   }
937
938 #ifdef DEBUG_DIRECTORY_TREE
939   LOG(astring("going to whack node at: ") + last_match->_dirname.raw());
940 #endif
941
942   // we're whacking directories, so we need to take out last_match and below.
943   filename_tree *parent = (filename_tree *)last_match->parent();
944   if (!parent || (last_match == _real_tree)) {
945     // this seems to be matching the whole tree.  we disallow that.
946 #ifdef DEBUG_DIRECTORY_TREE
947     LOG("there's a problem whacking this node; it's the root.");
948 #endif
949     return common::BAD_INPUT;
950   }
951 #ifdef DEBUG_DIRECTORY_TREE
952   LOG(astring("pruning tree at ") + last_match->_dirname.raw());
953 #endif
954   parent->prune(last_match);
955   WHACK(last_match);
956
957   return common::OKAY;
958 }
959
960 } //namespace.
961
962