summaryrefslogtreecommitdiff
path: root/src/generic/apt/tasks.cc
blob: 6c268b093c6d30125b071b43f562558ce83f0d95 (plain)
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
// tasks.cc
//
//  Copyright (C) 2001 Daniel Burrows
//  Copyright (C) 2012 Daniel Hartwig
//
//  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.,
//  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//

#include "tasks.h"
#include "apt.h"

#include <aptitude.h>

#include <apt-pkg/error.h>
#include <apt-pkg/pkgrecords.h>
#include <apt-pkg/tagfile.h>

#include <cwidget/generic/util/eassert.h>
#include <cwidget/generic/util/transcode.h>

#include <errno.h>
#include <ctype.h>

#include <map>
#include <vector>
#include <iterator>
#include <algorithm>
#include <sstream>

namespace cw = cwidget;

using namespace std;

namespace aptitude {
namespace apt {

// Stores the various tasks.
map<string, task> *task_list=new map<string, task>;

task *find_task(const std::string &name)
{
  if(task_list->find(name) == task_list->end())
    return NULL;

  return &((*task_list)[name]);
}

// This is an array indexed by package ID, managed by load_tasks.
// (as usual, it's initialized to NULL)
set<string> *tasks_by_package;

// Now this is just a wrapper, as you can see..
std::set<std::string> *get_tasks(const pkgCache::PkgIterator &pkg)
{
  if(!tasks_by_package)
    return NULL;

  return tasks_by_package+pkg->ID;
}

// Based on task_packages in tasksel.pl.
bool get_task_packages(std::set<pkgCache::PkgIterator> * const pkgset,
                       const task &task, const string &arch)
{
  // key packages are always included
  for(set<string>::const_iterator it = task.keys.begin();
      it != task.keys.end();
      ++it)
    {
      pkgCache::PkgIterator pkg = (*apt_cache_file)->FindPkg(*it, arch);
      if(pkg.end() != false)
        pkgset->insert(pkg);
    }

  if(task.packages.empty() == true)
    {
      // only key
    }
  else if(task.packages[0] == "task-fields")
    {
      // task-fields method is built-in for speed
      for(pkgCache::GrpIterator grp = (*apt_cache_file)->GrpBegin();
          grp.end() == false;
          ++grp)
        {
          pkgCache::PkgIterator pkg = grp.FindPkg(arch);
          if(pkg.end() == true)
            continue;
          set<string> *tasks = get_tasks(pkg);
          if(tasks->find(task.name) != tasks->end())
            pkgset->insert(pkg);
        }
    }
  else if(task.packages[0] == "list")
    {
      // list method is build-in for speed
      for(vector<string>::const_iterator it = task.packages.begin() + 1;
          it != task.packages.end();
          ++it)
        {
          const pkgCache::PkgIterator pkg = (*apt_cache_file)->FindPkg(*it, arch);
          if(pkg.end() != false)
            pkgset->insert(pkg);
        }
    }
  else
    {
      // TODO: Handle other methods.  One option is to just call
      // 'tasksel --task-packages' and process the list of search
      // patterns returned.
      return _error->Warning(_("Unhandled packages method in task %s: %s"),
                             task.name.c_str(),
                             task.packages[0].c_str());
    }

  return true;
}

bool is_task_package(const pkgCache::PkgIterator &pkg)
{
  // TODO: Enable this optimization on Debian systems.
  // if(pkg.Section() != NULL && strcmp(pkg.Section(), "tasks") == 0)
  //   return true;
  set<string> *pkg_tasks = get_tasks(pkg);
  for(set<string>::const_iterator it = pkg_tasks->begin();
      it != pkg_tasks->end();
      ++it)
    {
      if(task_list->find(*it) != task_list->end())
        {
          const task t = (*task_list)[*it];
          if(t.packages.empty() == true
             && t.keys.find(pkg.Name()) != t.keys.end())
            return true;
        }
    }

  return false;
}

/** \brief Add any tasks found in the given version-file pointer to
 *  the tasks of the given package.
 */
static void append_tasks(const pkgCache::PkgIterator &pkg,
			 const pkgCache::VerFileIterator &verfile)
{
  // This should never be called before load_tasks has initialized the
  // tasks structure.
  eassert(tasks_by_package);

  set<string> &task_set=tasks_by_package[pkg->ID];

  if(apt_package_records)
    {
      const char *start,*stop;
      pkgTagSection sec;

      // Pull out pointers to the underlying record.
      apt_package_records->Lookup(verfile).GetRec(start, stop);

      // Parse it as a section.
      sec.Scan(start, stop-start+1);

      string tasks=sec.FindS("Task");

      string::size_type loc=0, firstcomma=0;

      // Strip leading whitespace
      while(loc<tasks.size() && isspace(tasks[loc]))
	++loc;

      while( (firstcomma=tasks.find(',', loc))!=tasks.npos)
	{
	  // Strip trailing whitespace
	  string::size_type loc2=firstcomma-1;
	  while(isspace(tasks[loc2]))
	    --loc2;
	  ++loc2;

	  string taskname(tasks, loc, loc2-loc);
	  task_set.insert(taskname);
	  loc=firstcomma+1;

	  // Strip leading whitespace
	  while(loc<tasks.size() && isspace(tasks[loc]))
	    ++loc;
	}

      if(loc!=tasks.size())
	task_set.insert(string(tasks, loc));
    }
}

bool task::keys_present()
{
  if(!keys_present_cache_stale)
    return keys_present_cache;

  keys_present_cache_stale=false;

  for(set<string>::const_iterator i=keys.begin(); i!=keys.end(); ++i)
    {
      pkgCache::PkgIterator pkg=(*apt_cache_file)->FindPkg(*i);

      if(pkg.end())
	{
	  keys_present_cache=false;
	  return false;
	}
      else
	// Here it is assumed that all the tasks are loaded, because
	// we're going to look them up.
	{
	  set<string> *tasks = get_tasks(pkg);

	  if(!tasks)
	    {
	      keys_present_cache=false;
	      return false;
	    }

	  if(tasks->find(name) == tasks->end())
	    {
	      keys_present_cache=false;
	      return false;
	    }
	}
    }

  keys_present_cache=true;
  return true;
}

static string rfc822_process_paragraph(const string &textdomain,
				       string par)
{
  if (par.empty())
    return par;

  // Remove trailing whitespace
  string::size_type loc = par.size()-1;
  while(isspace(par[loc]))
    --loc;
  par.erase(loc+1, string::npos);

  return dgettext(textdomain.c_str(), par.c_str());
}

/** Returns msgid translated in the given text domain, with
 *  appropriate munging: paragraphs are translated individually after
 *  one leading and all trailing whitespace on each line is stripped.
 *
 *  \param textdomain the domain in which to translate
 *  \param msgid the formatted description which should be translated
 */
static string rfc822dgettext(string textdomain, string msgid)
{
  if (textdomain.empty())
    return msgid;
  string::size_type start=0, len=msgid.size(), nextnl=0;

  string thispar = "";
  string msgstr = "";

  // Remove leading whitespaces, i.e. replace "\n " by '\n'
  //
  // This assumes the trailing whitespace exists already.
  do
    {
      if (nextnl<len)
	nextnl=msgid.find('\n', start);
      if (nextnl==string::npos)
	nextnl=len-1;
      string thisline(msgid, start+1, nextnl-start);
      thispar+=thisline;
      start=nextnl+1;
    }
  while (start<len);

  // Reformat text (replace '\n' by ' ') and translate individual
  // paragraphs
  bool verbatimline = (thispar[0] == ' ');
  string::size_type loc=0;
  start=0, len=thispar.size(), nextnl=0;
  while((nextnl=thispar.find('\n', loc))!=string::npos)
    {
      // Verbatim line case
      if (thispar[nextnl+1] == ' ')
	verbatimline = true;
      // End of the paragraph
      else if (thispar[nextnl+1] == '.' && thispar[nextnl+2] == '\n')
	{
	  /* Translate current paragraph */
	  msgstr+=rfc822_process_paragraph(textdomain, string(thispar, start, nextnl-start));
	  msgstr+="\n.\n";
	  start = nextnl + 3;
	  nextnl += 2;
	  verbatimline = false;
	}
      // Add to the paragraph
      else
	{
	  if (!verbatimline)
	    thispar[nextnl] = ' ';
	  verbatimline = false;
	}
      loc = nextnl + 1;
    }
  msgstr+=rfc822_process_paragraph(textdomain, string(thispar, start));
  // Remove trailing whitespace
  loc=msgstr.size()-1;
  while(isspace(msgstr[loc]))
    --loc;
  ++loc;
  msgstr[loc] = '\0';
  // Reformat text, i.e. replace '\n' by "\n "
  start = 0;
  while((nextnl=msgstr.find('\n', start))!=string::npos)
    {
      msgstr.insert(nextnl+1, " ");
      start = nextnl+2;
    }
  return msgstr;
}

static void set_task_description(task &task, const wstring &desc)
{
  const wstring::size_type newline = desc.find(L'\n');
  task.shortdesc = wstring(desc, 0, newline);
  task.longdesc = wstring(L"\n ") + wstring(desc, newline+1);
}

static void read_task_desc(const string &filename, OpProgress &prog)
{
  FileFd fd;

  fd.Open(filename, FileFd::ReadOnly);
  if(!fd.IsOpen())
    return;

  const unsigned long long file_size = fd.Size();
  unsigned long long amt = 0;
  prog.SubProgress(file_size);

  pkgTagFile tagfile(&fd);
  pkgTagSection section;
  const string taskdomain("debian-tasks");

  while(tagfile.Step(section))
    {
      task newtask;
      const string taskname(section.FindS("Task"));

      if(!taskname.empty())
        {
          newtask.name = taskname;
          newtask.section = section.FindS("Section");
          newtask.relevance = section.FindI("Relevance", 5);

          istringstream keyss(section.FindS("Key"));
          for(istream_iterator<string> key(keyss);
              key != istream_iterator<string>();
              ++key)
            {
              newtask.keys.insert(*key);

              pkgCache::GrpIterator grp = (*apt_cache_file)->FindGrp(*key);
              if(grp.end() == true)
                continue;

              for(pkgCache::PkgIterator pkg = grp.PackageList();
                  pkg.end() == false;
                  pkg = pkg.Group().NextPkg(pkg))
                tasks_by_package[pkg->ID].insert(taskname);
            }

          istringstream packagess(section.FindS("Packages"));
          copy(istream_iterator<string>(packagess),
               istream_iterator<string>(),
               back_inserter(newtask.packages));

          string desc = section.FindS("Description");
          if(desc.empty() == false)
            {
              desc = rfc822dgettext(taskdomain, desc);
              set_task_description(newtask, cw::util::transcode(desc));
            }
          else
            {
              for(set<string>::const_iterator key = newtask.keys.begin();
                  key != newtask.keys.end();
                  ++key)
                {
                  const pkgCache::PkgIterator pkg((*apt_cache_file)->FindPkg(*key));
                  if(pkg.end() == true)
                    continue;
                  const pkgCache::VerIterator ver(pkg.VersionList());
                  if(ver.end() == true)
                    continue;

                  const wstring desc(get_long_description(ver, apt_package_records));
                  if(desc.empty() == true)
                    continue;

                  set_task_description(newtask, desc);
                  break;
                }
            }

          (*task_list)[taskname] = newtask;
        }

      amt += section.size();
      prog.Progress(amt);
    }
}

void load_tasks(OpProgress &progress)
{
  // Build a list for each package of the tasks that package belongs to.
  //
  // Sorting by location on disk is *critical* -- otherwise, this operation
  // will take ages.

  // This is done prior to loading the task descriptions so that I can just
  // bail if that fails.

  vector<loc_pair> versionfiles;

  for(pkgCache::PkgIterator pkg=(*apt_cache_file)->PkgBegin();
      !pkg.end(); ++pkg)
    {
      for(pkgCache::VerIterator v = pkg.VersionList(); !v.end(); ++v)
	{
	  for(pkgCache::VerFileIterator vf = v.FileList(); !vf.end(); ++vf)
	    {
	      versionfiles.push_back(loc_pair(v, vf));
	    }
	}
    }

  sort(versionfiles.begin(), versionfiles.end(), location_compare());

  // Allocate and set up the table of task information.
  delete[] tasks_by_package;
  tasks_by_package = new set<string>[(*apt_cache_file)->Head().PackageCount];

  for(vector<loc_pair>::iterator i=versionfiles.begin();
      i!=versionfiles.end();
      ++i)
    append_tasks(i->first.ParentPkg(), i->second);

  // Load the task descriptions:
  const char *descdirs[] =
    {"/usr/share/tasksel/descs",
     "/usr/local/share/tasksel/descs",
     NULL};
  vector<string> descfiles;
  for(const char **it = descdirs; *it != NULL; ++it)
    {
      if(DirectoryExists(*it) == false)
        continue;
      const vector<string> v =
        GetListOfFilesInDir(*it, "desc", false, false);
      copy(v.begin(), v.end(), back_inserter(descfiles));
    }
  for(vector<string>::const_iterator it = descfiles.begin();
      it != descfiles.end();
      ++it)
    {
      progress.OverallProgress(it - descfiles.begin(), descfiles.size(), 1,
                               _("Reading task descriptions"));
      read_task_desc(*it, progress);
    }

  progress.Done();
}

void reset_tasks()
{
  task_list->clear();
  delete[] tasks_by_package;
  tasks_by_package=NULL;
}

}
}