source: trunk/lib/File.cc @ 1005

Last change on this file since 1005 was 1005, checked in by Peter Johansson, 13 years ago

refs #405. Move replicated code to a function

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 13.0 KB
Line 
1// $Id: File.cc 1005 2010-01-03 03:05:25Z peter $
2
3/*
4  Copyright (C) 2005, 2006, 2007, 2008, 2009 Jari Häkkinen, Peter Johansson
5  Copyright (C) 2010 Peter Johansson
6
7  This file is part of svndigest, http://dev.thep.lu.se/svndigest
8
9  svndigest is free software; you can redistribute it and/or modify it
10  under the terms of the GNU General Public License as published by
11  the Free Software Foundation; either version 3 of the License, or
12  (at your option) any later version.
13
14  svndigest is distributed in the hope that it will be useful, but
15  WITHOUT ANY WARRANTY; without even the implied warranty of
16  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  General Public License for more details.
18
19  You should have received a copy of the GNU General Public License
20  along with svndigest. If not, see <http://www.gnu.org/licenses/>.
21*/
22
23#include "File.h"
24
25#include "Alias.h"
26#include "Colors.h"
27#include "Configuration.h"
28#include "Date.h"
29#include "Graph.h"
30#include "html_utility.h"
31#include "HtmlStream.h"
32#include "Stats.h"
33#include "SVNblame.h"
34#include "SVNlog.h"
35
36#include <algorithm>
37#include <cassert>
38#include <cstdio>
39#include <ctime>
40#include <fstream>
41#include <iostream>
42#include <map>
43#include <stdexcept>
44#include <string>
45#include <sstream>
46#include <sys/stat.h>
47
48namespace theplu{
49namespace svndigest{
50
51
52  File::File(const unsigned int level, const std::string& path, 
53             const std::string& output) 
54    : Node(level,path,output) 
55  {
56    output_dir_=output;
57    if (!output_dir_.empty())
58      output_dir_+='/';
59  }
60
61
62  std::string File::blame_output_file_name(void) const
63  {
64    return "blame_output/" + local_path() + ".html";
65  }
66
67
68  std::map<int, std::set<Alias> >
69  File::copyright_map(std::map<std::string, Alias>& alias,
70                      const std::map<int, svn_revnum_t>& year2rev) const
71  {
72    using namespace std;
73    map<int, set<Alias> > year_authors;
74    const Stats& stats = stats_["add"];
75
76    // loop over all years
77    for (std::map<int, svn_revnum_t>::const_iterator rev_iter=year2rev.begin();
78         rev_iter!=year2rev.end(); ++rev_iter) {
79
80      svn_revnum_t last_rev_this_year = rev_iter->second;
81      svn_revnum_t last_rev_last_year = 0;
82      if (rev_iter != year2rev.begin()) {
83        last_rev_last_year = (--rev_iter)->second;
84        ++rev_iter;
85      }
86      // do not go beyond BASE rev of file
87      last_rev_this_year = std::min(last_rev_this_year, last_changed_rev());
88      last_rev_last_year = std::min(last_rev_last_year, last_changed_rev());
89      // loop over authors
90      for (std::set<std::string>::const_iterator a_iter=stats.authors().begin();
91           a_iter!=stats.authors().end(); ++a_iter) {
92
93        // check if anything has been added since last year
94        if ( (stats(LineTypeParser::code, *a_iter, last_rev_this_year) >
95              stats(LineTypeParser::code, *a_iter, last_rev_last_year)) || 
96             (stats(LineTypeParser::comment, *a_iter, last_rev_this_year) >
97              stats(LineTypeParser::comment, *a_iter, last_rev_last_year)) ) {
98       
99       
100          // find username in map of aliases
101          std::map<string,Alias>::iterator name(alias.lower_bound(*a_iter));
102         
103          // if alias exist insert alias
104          if (name != alias.end() && name->first==*a_iter)
105            year_authors[rev_iter->first].insert(name->second);
106          else {
107            // else insert user name
108            Alias a(*a_iter,alias.size());
109            year_authors[rev_iter->first].insert(a);
110            std::cerr << "svndigest: warning: no copyright alias found for `" 
111                      << *a_iter << "'\n";
112            // insert alias to avoid multiple warnings.
113            alias.insert(name, std::make_pair(*a_iter, a));
114          }
115        }
116      }
117    }
118    return year_authors;
119  }
120
121
122  std::string
123  File::copyright_block(const std::map<int, std::set<Alias> >& year_authors,
124                        const std::string& prefix) const
125  {
126    using namespace std;
127    stringstream ss;
128    for (map<int, set<Alias> >::const_iterator i(year_authors.begin());
129         i!=year_authors.end();) {
130      ss << prefix << "Copyright (C) "
131          << 1900+i->first;
132      map<int, set<Alias> >::const_iterator j = i;
133      assert(i!=year_authors.end());
134      while (++j!=year_authors.end() && 
135             i->second == j->second){
136        ss << ", " << 1900+(j->first);
137      }
138      // printing authors
139      std::vector<Alias> vec_alias;
140      back_insert_iterator<std::vector<Alias> > ii(vec_alias);
141      std::copy(i->second.begin(), i->second.end(), ii);
142      // sort with respect to id
143      std::sort(vec_alias.begin(), vec_alias.end(), IdCompare());
144      for (std::vector<Alias>::iterator a=vec_alias.begin();
145           a!=vec_alias.end(); ++a){
146        if (a!=vec_alias.begin())
147          ss << ",";
148        ss << " " << a->name();
149      }
150      ss << "\n";
151      i = j;
152    }
153    return ss.str();
154  }
155
156  bool File::detect_copyright(std::string& block, size_t& start_at_line,
157                              size_t& end_at_line, std::string& prefix) const
158  {
159    using namespace std;
160    LineTypeParser parser(path());
161    std::ifstream is(path().c_str());
162    std::string line;
163    while (std::getline(is, line)) 
164      parser.parse(line);
165    if (!parser.copyright_found())
166      return false;
167    block = parser.block();
168    start_at_line = parser.start_line();
169    end_at_line = parser.end_line();
170    prefix = parser.prefix();
171    return true;
172  }
173
174
175  std::string File::href(void) const
176  { 
177    return name()+".html"; 
178  }
179
180
181  svn_revnum_t File::last_changed_rev(void) const
182  {
183    return svn_info().last_changed_rev();
184  }
185
186
187  void File::log_core(SVNlog&) const
188  {
189  }
190
191
192  std::string File::node_type(void) const
193  {
194    return std::string("file");
195  }
196
197
198  std::string File::output_path(void) const
199  {
200    return output_dir()+name()+".html";
201  }
202
203
204  const StatsCollection& File::parse(bool verbose, bool ignore)
205  {
206    if (verbose)
207      std::cout << "Parsing " << path_ << std::endl; 
208    stats_.reset();
209    std::string cache_dir = directory_name(path()) + std::string(".svndigest/"); 
210    std::string cache_file = cache_dir + name()+std::string(".svndigest-cache");
211    if (!ignore && node_exist(cache_file)){
212      std::ifstream is(cache_file.c_str());
213      if (stats_.load_cache(is)) {
214        is.close();
215        return stats_;
216      }
217      is.close();
218    }
219    else 
220      stats_.parse(path_);
221    if (!node_exist(cache_dir))
222      mkdir(cache_dir);
223    std::string tmp_cache_file(cache_file+"~");
224    std::ofstream os(tmp_cache_file.c_str());
225    stats_.print(os);
226    os.close();
227    rename(tmp_cache_file.c_str(), cache_file.c_str());
228    return stats_;
229  }
230
231
232  void File::print_blame(std::ofstream& os) const
233  {
234    os << "<br /><h3>" << local_path() << "</h3>";
235    os << "<div class=\"blame_legend\">\n";
236    os << "<dl>\n";
237    os << "<dt class=\"code\"></dt><dd>Code</dd>\n";
238    os << "<dt class=\"comment\"></dt><dd>Comments</dd>\n";
239    os << "<dt class=\"other\"></dt><dd>Other</dd>\n";
240    os << "</dl>\n</div>\n";
241    os << "<table class=\"blame\">\n";
242    os << "<thead>\n";
243    os << "<tr>\n";
244    os << "<th class=\"rev\">Rev</th>\n";
245    os << "<th class=\"date\">Date</th>\n";
246    os << "<th class=\"author\">Author</th>\n";
247    os << "<th class=\"line\">Line</th>\n";
248    os << "<th></th>\n";
249    os << "</tr>\n</thead>\n";
250    os << "<tbody>\n";
251    HtmlStream hs(os);
252    SVNblame blame(path_);
253    LineTypeParser parser(path_);
254    while (blame.valid()) {
255      parser.parse(blame.line());
256      blame.next_line();
257    }
258    blame.reset();
259
260    std::vector<LineTypeParser::line_type>::const_iterator
261      line_type(parser.type().begin());
262    int last=0;
263    int first=0;
264    bool using_dates=true;
265    if (!Graph::date_xticks()) {
266      using_dates=false;
267      last = stats_["classic"].revision();
268    }
269    else {
270      last = Date(Graph::xticks().back()).seconds();
271      // earliest date corresponds either to revision 0 or revision 1
272      first = std::min(Date(Graph::xticks()[0]).seconds(),
273                       Date(Graph::xticks()[1]).seconds());
274    }
275    // color is calculated linearly on time, c = kt + m
276    // brightest color (for oldest rev in log) is set to 192.
277    double k = 192.0/(first-last);
278    double m = -last*k; 
279    while (blame.valid()) {
280      std::string color;
281      if (using_dates)
282        color = hex(static_cast<int>(k*Date(blame.date()).seconds()+m),2);
283      else
284        color = hex(static_cast<int>(k*blame.revision()+m),2);
285      os << "<tr>\n<td class=\"rev\">";
286      std::stringstream color_ss;
287      color_ss << "#" << color << color << color; 
288      os << "<font color=\"" << color_ss.str() << "\">"
289         << trac_revision(blame.revision(), color_ss.str())
290         << "</font></td>\n<td class=\"date\"><font color=\"#" << color
291         << color << color << "\">" ;
292      hs << Date(blame.date())("%d %b %y");
293      os << "</font></td>\n<td class=\"author\">";
294      const std::string& author_color = 
295        Colors::instance().color_str(blame.author());
296      assert(!author_color.empty());
297      os << "<font color=\"#" << author_color << "\">";
298      hs << blame.author();
299      os << "</td>\n<td class=\"";
300      assert(line_type!=parser.type().end());
301      if (*line_type==LineTypeParser::other)
302        os << "line-other";
303      else if (*line_type==LineTypeParser::comment || 
304               *line_type==LineTypeParser::copyright)       
305        os << "line-comment";
306      else if (*line_type==LineTypeParser::code)
307        os << "line-code";
308      else {
309        std::string msg="File::print_blame(): unexpected line type found";
310        throw std::runtime_error(msg);
311      }
312      os << "\">" << blame.line_no()+1
313         << "</td>\n<td>";
314      hs << blame.line();
315      os << "</td>\n</tr>\n";
316      blame.next_line();
317      ++line_type;
318    }
319    os << "</tbody>\n";
320    os << "</table>\n";
321  }
322
323
324  void File::print_copyright(std::map<std::string, Alias>& alias, 
325                             bool verbose,
326                             const std::map<int,svn_revnum_t>& y2rev) const 
327  {
328    if (ignore())
329      return;
330
331    std::string old_block;
332    size_t start_line=0;
333    size_t end_line=0;
334    std::string prefix;
335    if (!detect_copyright(old_block, start_line, end_line, prefix)){
336      if (Configuration::instance().missing_copyright_warning())
337        std::cerr << "svndigest: warning: no copyright statement found in `" 
338                  << path_ << "'\n";
339      return;
340    }
341    std::map<int, std::set<Alias> > map=copyright_map(alias, y2rev);
342    std::string new_block = copyright_block(map, prefix);
343    if (old_block==new_block)
344      return;
345    if (verbose)
346      std::cout << "Updating copyright in " << path_ << std::endl; 
347    update_copyright(new_block, start_line, end_line);
348  }
349
350
351  void File::print_core(const bool verbose) const 
352  {
353    std::ofstream os(blame_output_file_name().c_str());
354    assert(os.good());
355    print_html_start(os, "svndigest", level_+1);
356    print_blame(os);
357    print_footer(os);
358    os.close();
359  }
360
361
362  void File::print_core(const std::string& stats_type, 
363                        const std::string& user, const std::string& line_type,
364                        const SVNlog& log) const 
365  {
366    std::string lpath = local_path();
367    if (lpath.empty())
368      lpath = "index";
369    std::string outpath = stats_type+"/"+user+"/"+line_type+"/"+lpath;
370    std::string imagefile = stats_type+"/"+"images/"+line_type+"/"+
371      lpath+".svg";
372    std::string html_name(outpath + ".html");
373    std::ofstream os(html_name.c_str());
374    print_header(os, name(), level_+3, user, line_type, lpath+".html",
375                 stats_type);
376    path_anchor(os);
377
378    std::stringstream ss;
379    for (size_t i=0; i<level_; ++i)
380      ss << "../";
381    ss << "../../../";
382    if (user=="all")
383      ss << stats_[stats_type].plot(imagefile,line_type);
384    else
385      ss << imagefile;
386    os << "<p class=\"plot\">\n"; 
387    os << image("svg", ss.str());
388    os << "</p>\n";
389
390    print_author_summary(os, stats_[stats_type], line_type, log);
391    os << "\n";
392    os << "<h3>"
393       << anchor(blame_output_file_name(), 
394                 "Blame Information", level_+3) 
395       << "</h3>\n";
396
397    print_footer(os);
398    os.close(); 
399  }
400
401  void File::update_copyright(const std::string& new_block,
402                              size_t start_at_line, size_t end_at_line) const
403  {
404    // Code copied from Gnuplot -r70
405    char tmpname[]="/tmp/svndigestXXXXXX";
406    int fd=mkstemp(tmpname);  // mkstemp return a file descriptor
407    if (fd == -1)
408      throw std::runtime_error(std::string("Failed to get unique filename: ") +
409                               tmpname);
410    // Jari would like to do something like 'std::ofstream tmp(fd);'
411    // but has to settle for (which is stupid since the file is
412    // already open for writing.
413    std::ofstream tmp(tmpname);
414
415    using namespace std;
416    ifstream is(path().c_str());
417    assert(is.good());
418    string line;
419    // Copy lines before block
420    for (size_t i=1; i<start_at_line; ++i){
421      assert(is.good());
422      getline(is, line);
423      tmp << line << "\n";
424    }
425    // Printing copyright statement
426    tmp << new_block;
427    // Ignore old block lines
428    for (size_t i=start_at_line; i<end_at_line; ++i){
429      assert(is.good());
430      getline(is, line);
431    }
432    // Copy lines after block
433    while(is.good()) {
434      char ch=is.get();
435      if (is.good())
436        tmp.put(ch);
437    }
438
439    is.close();
440    tmp.close();
441    close(fd);
442    // get file permission
443    struct stat nodestat;
444    stat(path().c_str(),&nodestat);
445   
446    // finally copy temporary file to replace original file, and
447    // remove the temporary file
448    try {
449      copy_file(tmpname, path());
450    }
451    catch (std::runtime_error e) {
452      // catch exception, cleanup, and rethrow
453      std::cerr << "svndigest: File::print_copyright: Exception caught, "
454                << "removing temporary file " << tmpname << std::endl;
455      if (unlink(tmpname))
456        throw runtime_error(std::string("File::print_copyright: ") +
457                            "failed to unlink temporary file" + tmpname);
458      throw;
459    }
460    if (unlink(tmpname))
461      throw runtime_error(std::string("File::print_copyright: ") +
462                          "failed to unlink temporary file" + tmpname);
463
464    chmod(path().c_str(), nodestat.st_mode);
465  }
466
467
468}} // end of namespace svndigest and namespace theplu
Note: See TracBrowser for help on using the repository browser.