cmCPackDebGenerator.cxx 30.7 KB
Newer Older
1 2
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */
Alexander Neundorf's avatar
 
Alexander Neundorf committed
3 4
#include "cmCPackDebGenerator.h"

5
#include "cmArchiveWrite.h"
Daniel Pfeifer's avatar
Daniel Pfeifer committed
6 7
#include "cmCPackComponentGroup.h"
#include "cmCPackGenerator.h"
8
#include "cmCPackLog.h"
9
#include "cmCryptoHash.h"
10
#include "cmGeneratedFileStream.h"
11
#include "cmStringAlgorithms.h"
12
#include "cmSystemTools.h"
13
#include "cm_sys_stat.h"
Alexander Neundorf's avatar
 
Alexander Neundorf committed
14

15
#include "cmsys/Glob.hxx"
16
#include <cstring>
17
#include <map>
Daniel Pfeifer's avatar
Daniel Pfeifer committed
18 19 20
#include <ostream>
#include <set>
#include <utility>
21

22 23 24 25 26
namespace {

class DebGenerator
{
public:
wahikihiki's avatar
wahikihiki committed
27 28
  DebGenerator(cmCPackLog* logger, std::string outputName, std::string workDir,
               std::string topLevelDir, std::string temporaryDir,
29 30
               const char* debianCompressionType,
               const char* debianArchiveType,
wahikihiki's avatar
wahikihiki committed
31 32 33 34 35
               std::map<std::string, std::string> controlValues,
               bool genShLibs, std::string shLibsFilename, bool genPostInst,
               std::string postInst, bool genPostRm, std::string postRm,
               const char* controlExtra, bool permissionStrctPolicy,
               std::vector<std::string> packageFiles);
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

  bool generate() const;

private:
  void generateDebianBinaryFile() const;
  void generateControlFile() const;
  bool generateDataTar() const;
  std::string generateMD5File() const;
  bool generateControlTar(std::string const& md5Filename) const;
  bool generateDeb() const;

  cmCPackLog* Logger;
  const std::string OutputName;
  const std::string WorkDir;
  std::string CompressionSuffix;
  const std::string TopLevelDir;
  const std::string TemporaryDir;
  const char* DebianArchiveType;
  const std::map<std::string, std::string> ControlValues;
  const bool GenShLibs;
  const std::string ShLibsFilename;
  const bool GenPostInst;
  const std::string PostInst;
  const bool GenPostRm;
  const std::string PostRm;
  const char* ControlExtra;
  const bool PermissionStrictPolicy;
  const std::vector<std::string> PackageFiles;
  cmArchiveWrite::Compress TarCompressionType;
};

DebGenerator::DebGenerator(
wahikihiki's avatar
wahikihiki committed
68 69 70 71 72 73 74
  cmCPackLog* logger, std::string outputName, std::string workDir,
  std::string topLevelDir, std::string temporaryDir,
  const char* debianCompressionType, const char* debianArchiveType,
  std::map<std::string, std::string> controlValues, bool genShLibs,
  std::string shLibsFilename, bool genPostInst, std::string postInst,
  bool genPostRm, std::string postRm, const char* controlExtra,
  bool permissionStrictPolicy, std::vector<std::string> packageFiles)
75
  : Logger(logger)
wahikihiki's avatar
wahikihiki committed
76 77 78 79
  , OutputName(std::move(outputName))
  , WorkDir(std::move(workDir))
  , TopLevelDir(std::move(topLevelDir))
  , TemporaryDir(std::move(temporaryDir))
80
  , DebianArchiveType(debianArchiveType ? debianArchiveType : "gnutar")
wahikihiki's avatar
wahikihiki committed
81
  , ControlValues(std::move(controlValues))
82
  , GenShLibs(genShLibs)
wahikihiki's avatar
wahikihiki committed
83
  , ShLibsFilename(std::move(shLibsFilename))
84
  , GenPostInst(genPostInst)
wahikihiki's avatar
wahikihiki committed
85
  , PostInst(std::move(postInst))
86
  , GenPostRm(genPostRm)
wahikihiki's avatar
wahikihiki committed
87
  , PostRm(std::move(postRm))
88 89
  , ControlExtra(controlExtra)
  , PermissionStrictPolicy(permissionStrictPolicy)
wahikihiki's avatar
wahikihiki committed
90
  , PackageFiles(std::move(packageFiles))
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
{
  if (!debianCompressionType) {
    debianCompressionType = "gzip";
  }

  if (!strcmp(debianCompressionType, "lzma")) {
    CompressionSuffix = ".lzma";
    TarCompressionType = cmArchiveWrite::CompressLZMA;
  } else if (!strcmp(debianCompressionType, "xz")) {
    CompressionSuffix = ".xz";
    TarCompressionType = cmArchiveWrite::CompressXZ;
  } else if (!strcmp(debianCompressionType, "bzip2")) {
    CompressionSuffix = ".bz2";
    TarCompressionType = cmArchiveWrite::CompressBZip2;
  } else if (!strcmp(debianCompressionType, "gzip")) {
    CompressionSuffix = ".gz";
    TarCompressionType = cmArchiveWrite::CompressGZip;
  } else if (!strcmp(debianCompressionType, "none")) {
    CompressionSuffix.clear();
    TarCompressionType = cmArchiveWrite::CompressNone;
  } else {
    cmCPackLogger(cmCPackLog::LOG_ERROR,
                  "Error unrecognized compression type: "
                    << debianCompressionType << std::endl);
  }
}

bool DebGenerator::generate() const
{
  generateDebianBinaryFile();
  generateControlFile();
  if (!generateDataTar()) {
    return false;
  }
  std::string md5Filename = generateMD5File();
  if (!generateControlTar(md5Filename)) {
    return false;
  }
  return generateDeb();
}

void DebGenerator::generateDebianBinaryFile() const
{
  // debian-binary file
  const std::string dbfilename = WorkDir + "/debian-binary";
  cmGeneratedFileStream out(dbfilename);
  out << "2.0";
  out << std::endl; // required for valid debian package
}

void DebGenerator::generateControlFile() const
{
  std::string ctlfilename = WorkDir + "/control";

  cmGeneratedFileStream out(ctlfilename);
  for (auto const& kv : ControlValues) {
    out << kv.first << ": " << kv.second << "\n";
  }

  unsigned long totalSize = 0;
  {
152
    std::string dirName = cmStrCat(TemporaryDir, '/');
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
    for (std::string const& file : PackageFiles) {
      totalSize += cmSystemTools::FileLength(file);
    }
  }
  out << "Installed-Size: " << (totalSize + 1023) / 1024 << "\n";
  out << std::endl;
}

bool DebGenerator::generateDataTar() const
{
  std::string filename_data_tar = WorkDir + "/data.tar" + CompressionSuffix;
  cmGeneratedFileStream fileStream_data_tar;
  fileStream_data_tar.Open(filename_data_tar, false, true);
  if (!fileStream_data_tar) {
    cmCPackLogger(cmCPackLog::LOG_ERROR,
                  "Error opening the file \""
                    << filename_data_tar << "\" for writing" << std::endl);
    return false;
  }
  cmArchiveWrite data_tar(fileStream_data_tar, TarCompressionType,
                          DebianArchiveType);

  // uid/gid should be the one of the root user, and this root user has
  // always uid/gid equal to 0.
  data_tar.SetUIDAndGID(0u, 0u);
  data_tar.SetUNAMEAndGNAME("root", "root");

  // now add all directories which have to be compressed
  // collect all top level install dirs for that
  // e.g. /opt/bin/foo, /usr/bin/bar and /usr/bin/baz would
  // give /usr and /opt
  size_t topLevelLength = WorkDir.length();
  cmCPackLogger(cmCPackLog::LOG_DEBUG,
                "WDIR: \"" << WorkDir << "\", length = " << topLevelLength
                           << std::endl);
  std::set<std::string> orderedFiles;

  // we have to reconstruct the parent folders as well

  for (std::string currentPath : PackageFiles) {
    while (currentPath != WorkDir) {
      // the last one IS WorkDir, but we do not want this one:
      // XXX/application/usr/bin/myprogram with GEN_WDIR=XXX/application
      // should not add XXX/application
      orderedFiles.insert(currentPath);
198
      currentPath = cmSystemTools::CollapseFullPath("..", currentPath);
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
    }
  }

  for (std::string const& file : orderedFiles) {
    cmCPackLogger(cmCPackLog::LOG_DEBUG,
                  "FILEIT: \"" << file << "\"" << std::endl);
    std::string::size_type slashPos = file.find('/', topLevelLength + 1);
    std::string relativeDir =
      file.substr(topLevelLength, slashPos - topLevelLength);
    cmCPackLogger(cmCPackLog::LOG_DEBUG,
                  "RELATIVEDIR: \"" << relativeDir << "\"" << std::endl);

#ifdef WIN32
    std::string mode_t_adt_filename = file + ":cmake_mode_t";
    cmsys::ifstream permissionStream(mode_t_adt_filename.c_str());

    mode_t permissions = 0;

    if (permissionStream) {
      permissionStream >> std::oct >> permissions;
    }

    if (permissions != 0) {
      data_tar.SetPermissions(permissions);
    } else if (cmSystemTools::FileIsDirectory(file)) {
      data_tar.SetPermissions(0755);
    } else {
      data_tar.ClearPermissions();
    }
#endif

    // do not recurse because the loop will do it
    if (!data_tar.Add(file, topLevelLength, ".", false)) {
      cmCPackLogger(cmCPackLog::LOG_ERROR,
                    "Problem adding file to tar:"
                      << std::endl
                      << "#top level directory: " << WorkDir << std::endl
                      << "#file: " << file << std::endl
                      << "#error:" << data_tar.GetError() << std::endl);
      return false;
    }
  }
  return true;
}

std::string DebGenerator::generateMD5File() const
{
  std::string md5filename = WorkDir + "/md5sums";

  cmGeneratedFileStream out(md5filename);

250
  std::string topLevelWithTrailingSlash = cmStrCat(TemporaryDir, '/');
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
  for (std::string const& file : PackageFiles) {
    // hash only regular files
    if (cmSystemTools::FileIsDirectory(file) ||
        cmSystemTools::FileIsSymlink(file)) {
      continue;
    }

    std::string output =
      cmSystemTools::ComputeFileHash(file, cmCryptoHash::AlgoMD5);
    if (output.empty()) {
      cmCPackLogger(cmCPackLog::LOG_ERROR,
                    "Problem computing the md5 of " << file << std::endl);
    }

    output += "  " + file + "\n";
    // debian md5sums entries are like this:
    // 014f3604694729f3bf19263bac599765  usr/bin/ccmake
    // thus strip the full path (with the trailing slash)
    cmSystemTools::ReplaceString(output, topLevelWithTrailingSlash.c_str(),
                                 "");
    out << output;
  }
  // each line contains a eol.
  // Do not end the md5sum file with yet another (invalid)
  return md5filename;
}

bool DebGenerator::generateControlTar(std::string const& md5Filename) const
{
  std::string filename_control_tar = WorkDir + "/control.tar.gz";

  cmGeneratedFileStream fileStream_control_tar;
  fileStream_control_tar.Open(filename_control_tar, false, true);
  if (!fileStream_control_tar) {
    cmCPackLogger(cmCPackLog::LOG_ERROR,
                  "Error opening the file \""
                    << filename_control_tar << "\" for writing" << std::endl);
    return false;
  }
  cmArchiveWrite control_tar(fileStream_control_tar,
                             cmArchiveWrite::CompressGZip, DebianArchiveType);

  // sets permissions and uid/gid for the files
  control_tar.SetUIDAndGID(0u, 0u);
  control_tar.SetUNAMEAndGNAME("root", "root");

  /* permissions are set according to
  https://www.debian.org/doc/debian-policy/ch-files.html#s-permissions-owners
  and
  https://lintian.debian.org/tags/control-file-has-bad-permissions.html
  */
  const mode_t permission644 = 0644;
  const mode_t permissionExecute = 0111;
  const mode_t permission755 = permission644 | permissionExecute;

  // for md5sum and control (that we have generated here), we use 644
  // (RW-R--R--)
  // so that deb lintian doesn't warn about it
  control_tar.SetPermissions(permission644);

  // adds control and md5sums
  if (!control_tar.Add(md5Filename, WorkDir.length(), ".") ||
      !control_tar.Add(WorkDir + "/control", WorkDir.length(), ".")) {
    cmCPackLogger(cmCPackLog::LOG_ERROR,
                  "Error adding file to tar:"
                    << std::endl
                    << "#top level directory: " << WorkDir << std::endl
                    << "#file: \"control\" or \"md5sums\"" << std::endl
                    << "#error:" << control_tar.GetError() << std::endl);
    return false;
  }

  // adds generated shlibs file
  if (GenShLibs) {
    if (!control_tar.Add(ShLibsFilename, WorkDir.length(), ".")) {
      cmCPackLogger(cmCPackLog::LOG_ERROR,
                    "Error adding file to tar:"
                      << std::endl
                      << "#top level directory: " << WorkDir << std::endl
                      << "#file: \"shlibs\"" << std::endl
                      << "#error:" << control_tar.GetError() << std::endl);
      return false;
    }
  }

  // adds LDCONFIG related files
  if (GenPostInst) {
    control_tar.SetPermissions(permission755);
    if (!control_tar.Add(PostInst, WorkDir.length(), ".")) {
      cmCPackLogger(cmCPackLog::LOG_ERROR,
                    "Error adding file to tar:"
                      << std::endl
                      << "#top level directory: " << WorkDir << std::endl
                      << "#file: \"postinst\"" << std::endl
                      << "#error:" << control_tar.GetError() << std::endl);
      return false;
    }
    control_tar.SetPermissions(permission644);
  }

  if (GenPostRm) {
    control_tar.SetPermissions(permission755);
    if (!control_tar.Add(PostRm, WorkDir.length(), ".")) {
      cmCPackLogger(cmCPackLog::LOG_ERROR,
                    "Error adding file to tar:"
                      << std::endl
                      << "#top level directory: " << WorkDir << std::endl
                      << "#file: \"postinst\"" << std::endl
                      << "#error:" << control_tar.GetError() << std::endl);
      return false;
    }
    control_tar.SetPermissions(permission644);
  }

  // for the other files, we use
  // -either the original permission on the files
  // -either a permission strictly defined by the Debian policies
  if (ControlExtra) {
    // permissions are now controlled by the original file permissions

    static const char* strictFiles[] = { "config", "postinst", "postrm",
                                         "preinst", "prerm" };
    std::set<std::string> setStrictFiles(
      strictFiles, strictFiles + sizeof(strictFiles) / sizeof(strictFiles[0]));

    // default
    control_tar.ClearPermissions();

379
    std::vector<std::string> controlExtraList = cmExpandedList(ControlExtra);
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
    for (std::string const& i : controlExtraList) {
      std::string filenamename = cmsys::SystemTools::GetFilenameName(i);
      std::string localcopy = WorkDir + "/" + filenamename;

      if (PermissionStrictPolicy) {
        control_tar.SetPermissions(
          setStrictFiles.count(filenamename) ? permission755 : permission644);
      }

      // if we can copy the file, it means it does exist, let's add it:
      if (cmsys::SystemTools::CopyFileIfDifferent(i, localcopy)) {
        control_tar.Add(localcopy, WorkDir.length(), ".");
      }
    }
  }

  return true;
}

bool DebGenerator::generateDeb() const
{
  // ar -r your-package-name.deb debian-binary control.tar.* data.tar.*
  // A debian package .deb is simply an 'ar' archive. The only subtle
  // difference is that debian uses the BSD ar style archive whereas most
  // Linux distro have a GNU ar.
  // See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=161593 for more info
  std::string const outputPath = TopLevelDir + "/" + OutputName;
  std::string const tlDir = WorkDir + "/";
  cmGeneratedFileStream debStream;
  debStream.Open(outputPath, false, true);
  cmArchiveWrite deb(debStream, cmArchiveWrite::CompressNone, "arbsd");

  // uid/gid should be the one of the root user, and this root user has
  // always uid/gid equal to 0.
  deb.SetUIDAndGID(0u, 0u);
  deb.SetUNAMEAndGNAME("root", "root");

  if (!deb.Add(tlDir + "debian-binary", tlDir.length()) ||
      !deb.Add(tlDir + "control.tar.gz", tlDir.length()) ||
      !deb.Add(tlDir + "data.tar" + CompressionSuffix, tlDir.length())) {
    cmCPackLogger(cmCPackLog::LOG_ERROR,
                  "Error creating debian package:"
                    << std::endl
                    << "#top level directory: " << TopLevelDir << std::endl
                    << "#file: " << OutputName << std::endl
                    << "#error:" << deb.GetError() << std::endl);
    return false;
  }
  return true;
}

} // end anonymous namespace

wahikihiki's avatar
wahikihiki committed
433
cmCPackDebGenerator::cmCPackDebGenerator() = default;
Alexander Neundorf's avatar
 
Alexander Neundorf committed
434

wahikihiki's avatar
wahikihiki committed
435
cmCPackDebGenerator::~cmCPackDebGenerator() = default;
Alexander Neundorf's avatar
 
Alexander Neundorf committed
436

437 438 439
int cmCPackDebGenerator::InitializeInternal()
{
  this->SetOptionIfNotSet("CPACK_PACKAGING_INSTALL_PREFIX", "/usr");
440
  if (cmIsOff(this->GetOption("CPACK_SET_DESTDIR"))) {
441
    this->SetOption("CPACK_SET_DESTDIR", "I_ON");
442
  }
443 444 445
  return this->Superclass::InitializeInternal();
}

446 447
int cmCPackDebGenerator::PackageOnePack(std::string const& initialTopLevel,
                                        std::string const& packageName)
448
{
449 450 451
  int retval = 1;
  // Begin the archive for this pack
  std::string localToplevel(initialTopLevel);
452
  std::string packageFileName(cmSystemTools::GetParentDirectory(toplevel));
453 454 455
  std::string outputFileName(
    std::string(this->GetOption("CPACK_PACKAGE_FILE_NAME")) + "-" +
    packageName + this->GetOutputExtension());
456 457

  localToplevel += "/" + packageName;
458
  /* replace the TEMP DIRECTORY with the component one */
459 460
  this->SetOption("CPACK_TEMPORARY_DIRECTORY", localToplevel.c_str());
  packageFileName += "/" + outputFileName;
461
  /* replace proposed CPACK_OUTPUT_FILE_NAME */
462
  this->SetOption("CPACK_OUTPUT_FILE_NAME", outputFileName.c_str());
463 464
  /* replace the TEMPORARY package file name */
  this->SetOption("CPACK_TEMPORARY_PACKAGE_FILE_NAME",
465
                  packageFileName.c_str());
466
  // Tell CPackDeb.cmake the name of the component GROUP.
467
  this->SetOption("CPACK_DEB_PACKAGE_COMPONENT", packageName.c_str());
468
  // Tell CPackDeb.cmake the path where the component is.
469
  std::string component_path = cmStrCat('/', packageName);
470 471
  this->SetOption("CPACK_DEB_PACKAGE_COMPONENT_PART_PATH",
                  component_path.c_str());
472
  if (!this->ReadListFile("Internal/CPack/CPackDeb.cmake")) {
473 474
    cmCPackLogger(cmCPackLog::LOG_ERROR,
                  "Error while execution CPackDeb.cmake" << std::endl);
475 476
    retval = 0;
    return retval;
477
  }
478

479 480 481 482 483 484 485 486 487 488 489 490 491
  { // Isolate globbing of binaries vs. dbgsyms
    cmsys::Glob gl;
    std::string findExpr(this->GetOption("GEN_WDIR"));
    findExpr += "/*";
    gl.RecurseOn();
    gl.SetRecurseListDirs(true);
    if (!gl.FindFiles(findExpr)) {
      cmCPackLogger(cmCPackLog::LOG_ERROR,
                    "Cannot find any files in the installed directory"
                      << std::endl);
      return 0;
    }
    packageFiles = gl.GetFiles();
492
  }
493 494

  int res = createDeb();
495
  if (res != 1) {
496
    retval = 0;
497
  }
498
  // add the generated package to package file names list
499 500
  packageFileName = cmStrCat(this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), '/',
                             this->GetOption("GEN_CPACK_OUTPUT_FILE_NAME"));
501
  packageFileNames.push_back(std::move(packageFileName));
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521

  if (this->IsOn("GEN_CPACK_DEBIAN_DEBUGINFO_PACKAGE")) {
    cmsys::Glob gl;
    std::string findExpr(this->GetOption("GEN_DBGSYMDIR"));
    findExpr += "/*";
    gl.RecurseOn();
    gl.SetRecurseListDirs(true);
    if (!gl.FindFiles(findExpr)) {
      cmCPackLogger(cmCPackLog::LOG_ERROR,
                    "Cannot find any files in the installed directory"
                      << std::endl);
      return 0;
    }
    packageFiles = gl.GetFiles();

    res = createDbgsymDDeb();
    if (res != 1) {
      retval = 0;
    }
    // add the generated package to package file names list
522 523 524
    packageFileName =
      cmStrCat(this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), '/',
               this->GetOption("GEN_CPACK_DBGSYM_OUTPUT_FILE_NAME"));
525 526 527
    packageFileNames.push_back(std::move(packageFileName));
  }

528 529 530
  return retval;
}

531 532 533 534 535 536 537 538 539 540
int cmCPackDebGenerator::PackageComponents(bool ignoreGroup)
{
  int retval = 1;
  /* Reset package file name list it will be populated during the
   * component packaging run*/
  packageFileNames.clear();
  std::string initialTopLevel(this->GetOption("CPACK_TEMPORARY_DIRECTORY"));

  // The default behavior is to have one package by component group
  // unless CPACK_COMPONENTS_IGNORE_GROUP is specified.
541
  if (!ignoreGroup) {
542 543 544
    for (auto const& compG : this->ComponentGroups) {
      cmCPackLogger(cmCPackLog::LOG_VERBOSE,
                    "Packaging component group: " << compG.first << std::endl);
545
      // Begin the archive for this group
546
      retval &= PackageOnePack(initialTopLevel, compG.first);
547
    }
548
    // Handle Orphan components (components not belonging to any groups)
549
    for (auto const& comp : this->Components) {
550
      // Does the component belong to a group?
551
      if (comp.second.Group == nullptr) {
552
        cmCPackLogger(
553 554
          cmCPackLog::LOG_VERBOSE,
          "Component <"
555
            << comp.second.Name
556 557 558
            << "> does not belong to any group, package it separately."
            << std::endl);
        // Begin the archive for this orphan component
559
        retval &= PackageOnePack(initialTopLevel, comp.first);
560 561
      }
    }
562
  }
563 564
  // CPACK_COMPONENTS_IGNORE_GROUPS is set
  // We build 1 package per component
565
  else {
566 567
    for (auto const& comp : this->Components) {
      retval &= PackageOnePack(initialTopLevel, comp.first);
568
    }
569
  }
570 571 572
  return retval;
}

573 574
//----------------------------------------------------------------------
int cmCPackDebGenerator::PackageComponentsAllInOne(
575
  const std::string& compInstDirName)
576 577 578 579 580 581 582 583 584 585
{
  int retval = 1;
  /* Reset package file name list it will be populated during the
   * component packaging run*/
  packageFileNames.clear();
  std::string initialTopLevel(this->GetOption("CPACK_TEMPORARY_DIRECTORY"));

  cmCPackLogger(cmCPackLog::LOG_VERBOSE,
                "Packaging all groups in one package..."
                "(CPACK_COMPONENTS_ALL_[GROUPS_]IN_ONE_PACKAGE is set)"
586
                  << std::endl);
587 588 589

  // The ALL GROUPS in ONE package case
  std::string localToplevel(initialTopLevel);
590
  std::string packageFileName(cmSystemTools::GetParentDirectory(toplevel));
591 592 593
  std::string outputFileName(
    std::string(this->GetOption("CPACK_PACKAGE_FILE_NAME")) +
    this->GetOutputExtension());
594
  // all GROUP in one vs all COMPONENT in one
595 596 597 598 599
  // if must be here otherwise non component paths have a trailing / while
  // components don't
  if (!compInstDirName.empty()) {
    localToplevel += "/" + compInstDirName;
  }
600 601

  /* replace the TEMP DIRECTORY with the component one */
602 603
  this->SetOption("CPACK_TEMPORARY_DIRECTORY", localToplevel.c_str());
  packageFileName += "/" + outputFileName;
604
  /* replace proposed CPACK_OUTPUT_FILE_NAME */
605
  this->SetOption("CPACK_OUTPUT_FILE_NAME", outputFileName.c_str());
606 607
  /* replace the TEMPORARY package file name */
  this->SetOption("CPACK_TEMPORARY_PACKAGE_FILE_NAME",
608
                  packageFileName.c_str());
609

610
  if (!compInstDirName.empty()) {
611
    // Tell CPackDeb.cmake the path where the component is.
612
    std::string component_path = cmStrCat('/', compInstDirName);
613 614
    this->SetOption("CPACK_DEB_PACKAGE_COMPONENT_PART_PATH",
                    component_path.c_str());
615
  }
616
  if (!this->ReadListFile("Internal/CPack/CPackDeb.cmake")) {
617 618
    cmCPackLogger(cmCPackLog::LOG_ERROR,
                  "Error while execution CPackDeb.cmake" << std::endl);
619
    retval = 0;
620
    return retval;
621
  }
622 623

  cmsys::Glob gl;
624
  std::string findExpr(this->GetOption("GEN_WDIR"));
625 626
  findExpr += "/*";
  gl.RecurseOn();
627
  gl.SetRecurseListDirs(true);
628
  if (!gl.FindFiles(findExpr)) {
629
    cmCPackLogger(cmCPackLog::LOG_ERROR,
630 631
                  "Cannot find any files in the installed directory"
                    << std::endl);
632
    return 0;
633
  }
634 635 636
  packageFiles = gl.GetFiles();

  int res = createDeb();
637
  if (res != 1) {
638
    retval = 0;
639
  }
640
  // add the generated package to package file names list
641 642
  packageFileName = cmStrCat(this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), '/',
                             this->GetOption("GEN_CPACK_OUTPUT_FILE_NAME"));
643
  packageFileNames.push_back(std::move(packageFileName));
644 645 646
  return retval;
}

647
int cmCPackDebGenerator::PackageFiles()
Alexander Neundorf's avatar
 
Alexander Neundorf committed
648
{
649
  /* Are we in the component packaging case */
650
  if (WantsComponentInstallation()) {
651 652 653
    // CASE 1 : COMPONENT ALL-IN-ONE package
    // If ALL GROUPS or ALL COMPONENTS in ONE package has been requested
    // then the package file is unique and should be open here.
654
    if (componentPackageMethod == ONE_PACKAGE) {
655
      return PackageComponentsAllInOne("ALL_COMPONENTS_IN_ONE");
656
    }
657 658 659 660
    // CASE 2 : COMPONENT CLASSICAL package(s) (i.e. not all-in-one)
    // There will be 1 package for each component group
    // however one may require to ignore component group and
    // in this case you'll get 1 package for each component.
661 662
    return PackageComponents(componentPackageMethod ==
                             ONE_PACKAGE_PER_COMPONENT);
663 664
  }
  // CASE 3 : NON COMPONENT package.
665
  return PackageComponentsAllInOne("");
666 667 668 669
}

int cmCPackDebGenerator::createDeb()
{
670
  std::map<std::string, std::string> controlValues;
Alexander Neundorf's avatar
 
Alexander Neundorf committed
671 672

  // debian policy enforce lower case for package name
673
  controlValues["Package"] = cmsys::SystemTools::LowerCase(
674
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_NAME"));
675
  controlValues["Version"] =
676
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_VERSION");
677
  controlValues["Section"] =
678
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SECTION");
679
  controlValues["Priority"] =
680
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_PRIORITY");
681
  controlValues["Architecture"] =
682
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_ARCHITECTURE");
683
  controlValues["Maintainer"] =
684
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_MAINTAINER");
685 686
  controlValues["Description"] =
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_DESCRIPTION");
Alexander Neundorf's avatar
 
Alexander Neundorf committed
687

688 689 690 691 692
  const char* debian_pkg_source =
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SOURCE");
  if (debian_pkg_source && *debian_pkg_source) {
    controlValues["Source"] = debian_pkg_source;
  }
693
  const char* debian_pkg_dep =
694
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_DEPENDS");
695 696 697
  if (debian_pkg_dep && *debian_pkg_dep) {
    controlValues["Depends"] = debian_pkg_dep;
  }
698
  const char* debian_pkg_rec =
699
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_RECOMMENDS");
700 701 702
  if (debian_pkg_rec && *debian_pkg_rec) {
    controlValues["Recommends"] = debian_pkg_rec;
  }
703
  const char* debian_pkg_sug =
704
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SUGGESTS");
705 706 707
  if (debian_pkg_sug && *debian_pkg_sug) {
    controlValues["Suggests"] = debian_pkg_sug;
  }
708
  const char* debian_pkg_url =
709
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_HOMEPAGE");
710 711 712
  if (debian_pkg_url && *debian_pkg_url) {
    controlValues["Homepage"] = debian_pkg_url;
  }
713
  const char* debian_pkg_predep =
714
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_PREDEPENDS");
715 716 717
  if (debian_pkg_predep && *debian_pkg_predep) {
    controlValues["Pre-Depends"] = debian_pkg_predep;
  }
718
  const char* debian_pkg_enhances =
719
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_ENHANCES");
720 721 722
  if (debian_pkg_enhances && *debian_pkg_enhances) {
    controlValues["Enhances"] = debian_pkg_enhances;
  }
723
  const char* debian_pkg_breaks =
724
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_BREAKS");
725 726 727
  if (debian_pkg_breaks && *debian_pkg_breaks) {
    controlValues["Breaks"] = debian_pkg_breaks;
  }
728
  const char* debian_pkg_conflicts =
729
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_CONFLICTS");
730 731 732
  if (debian_pkg_conflicts && *debian_pkg_conflicts) {
    controlValues["Conflicts"] = debian_pkg_conflicts;
  }
733
  const char* debian_pkg_provides =
734
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_PROVIDES");
735 736 737
  if (debian_pkg_provides && *debian_pkg_provides) {
    controlValues["Provides"] = debian_pkg_provides;
  }
738
  const char* debian_pkg_replaces =
739
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_REPLACES");
740 741
  if (debian_pkg_replaces && *debian_pkg_replaces) {
    controlValues["Replaces"] = debian_pkg_replaces;
742
  }
Alexander Neundorf's avatar
 
Alexander Neundorf committed
743

744
  const std::string strGenWDIR(this->GetOption("GEN_WDIR"));
745 746
  const std::string shlibsfilename = strGenWDIR + "/shlibs";

747 748 749 750 751
  const char* debian_pkg_shlibs =
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SHLIBS");
  const bool gen_shibs = this->IsOn("CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS") &&
    debian_pkg_shlibs && *debian_pkg_shlibs;
  if (gen_shibs) {
752
    cmGeneratedFileStream out(shlibsfilename);
753 754
    out << debian_pkg_shlibs;
    out << std::endl;
755
  }
756

757 758
  const std::string postinst = strGenWDIR + "/postinst";
  const std::string postrm = strGenWDIR + "/postrm";
759
  if (this->IsOn("GEN_CPACK_DEBIAN_GENERATE_POSTINST")) {
760
    cmGeneratedFileStream out(postinst);
761 762 763 764 765 766 767
    out << "#!/bin/sh\n\n"
           "set -e\n\n"
           "if [ \"$1\" = \"configure\" ]; then\n"
           "\tldconfig\n"
           "fi\n";
  }
  if (this->IsOn("GEN_CPACK_DEBIAN_GENERATE_POSTRM")) {
768
    cmGeneratedFileStream out(postrm);
769 770 771 772 773 774
    out << "#!/bin/sh\n\n"
           "set -e\n\n"
           "if [ \"$1\" = \"remove\" ]; then\n"
           "\tldconfig\n"
           "fi\n";
  }
775

776 777 778 779 780 781 782 783 784 785 786 787 788 789
  DebGenerator gen(
    Logger, this->GetOption("GEN_CPACK_OUTPUT_FILE_NAME"), strGenWDIR,
    this->GetOption("CPACK_TOPLEVEL_DIRECTORY"),
    this->GetOption("CPACK_TEMPORARY_DIRECTORY"),
    this->GetOption("GEN_CPACK_DEBIAN_COMPRESSION_TYPE"),
    this->GetOption("GEN_CPACK_DEBIAN_ARCHIVE_TYPE"), controlValues, gen_shibs,
    shlibsfilename, this->IsOn("GEN_CPACK_DEBIAN_GENERATE_POSTINST"), postinst,
    this->IsOn("GEN_CPACK_DEBIAN_GENERATE_POSTRM"), postrm,
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA"),
    this->IsSet("GEN_CPACK_DEBIAN_PACKAGE_CONTROL_STRICT_PERMISSION"),
    packageFiles);

  if (!gen.generate()) {
    return 0;
790
  }
791 792
  return 1;
}
793

794 795 796 797
int cmCPackDebGenerator::createDbgsymDDeb()
{
  // Packages containing debug symbols follow the same structure as .debs
  // but have different metadata and content.
Alexander Neundorf's avatar
 
Alexander Neundorf committed
798

799 800 801 802 803 804
  std::map<std::string, std::string> controlValues;
  // debian policy enforce lower case for package name
  std::string packageNameLower = cmsys::SystemTools::LowerCase(
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_NAME"));
  const char* debian_pkg_version =
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_VERSION");
805

806 807 808 809 810 811 812 813 814 815 816 817 818 819
  controlValues["Package"] = packageNameLower + "-dbgsym";
  controlValues["Package-Type"] = "ddeb";
  controlValues["Version"] = debian_pkg_version;
  controlValues["Auto-Built-Package"] = "debug-symbols";
  controlValues["Depends"] = this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_NAME") +
    std::string(" (= ") + debian_pkg_version + ")";
  controlValues["Section"] = "debug";
  controlValues["Priority"] = "optional";
  controlValues["Architecture"] =
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_ARCHITECTURE");
  controlValues["Maintainer"] =
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_MAINTAINER");
  controlValues["Description"] =
    std::string("debug symbols for ") + packageNameLower;
820

821 822 823 824
  const char* debian_pkg_source =
    this->GetOption("GEN_CPACK_DEBIAN_PACKAGE_SOURCE");
  if (debian_pkg_source && *debian_pkg_source) {
    controlValues["Source"] = debian_pkg_source;
825
  }
826 827 828
  const char* debian_build_ids = this->GetOption("GEN_BUILD_IDS");
  if (debian_build_ids && *debian_build_ids) {
    controlValues["Build-Ids"] = debian_build_ids;
829
  }
Alexander Neundorf's avatar
 
Alexander Neundorf committed
830

831 832 833
  DebGenerator gen(
    Logger, this->GetOption("GEN_CPACK_DBGSYM_OUTPUT_FILE_NAME"),
    this->GetOption("GEN_DBGSYMDIR"),
834

835 836 837 838 839 840 841
    this->GetOption("CPACK_TOPLEVEL_DIRECTORY"),
    this->GetOption("CPACK_TEMPORARY_DIRECTORY"),
    this->GetOption("GEN_CPACK_DEBIAN_COMPRESSION_TYPE"),
    this->GetOption("GEN_CPACK_DEBIAN_ARCHIVE_TYPE"), controlValues, false, "",
    false, "", false, "", nullptr,
    this->IsSet("GEN_CPACK_DEBIAN_PACKAGE_CONTROL_STRICT_PERMISSION"),
    packageFiles);
842

843
  if (!gen.generate()) {
Alexander Neundorf's avatar
 
Alexander Neundorf committed
844
    return 0;
845
  }
Alexander Neundorf's avatar
 
Alexander Neundorf committed
846 847 848
  return 1;
}

849
bool cmCPackDebGenerator::SupportsComponentInstallation() const
850
{
Daniel Pfeifer's avatar
Daniel Pfeifer committed
851
  return IsOn("CPACK_DEB_COMPONENT_INSTALL");
852
}
853 854

std::string cmCPackDebGenerator::GetComponentInstallDirNameSuffix(
855 856
  const std::string& componentName)
{
857
  if (componentPackageMethod == ONE_PACKAGE_PER_COMPONENT) {
858 859 860
    return componentName;
  }

861
  if (componentPackageMethod == ONE_PACKAGE) {
862 863 864 865
    return std::string("ALL_COMPONENTS_IN_ONE");
  }
  // We have to find the name of the COMPONENT GROUP
  // the current COMPONENT belongs to.
866 867
  std::string groupVar =
    "CPACK_COMPONENT_" + cmSystemTools::UpperCase(componentName) + "_GROUP";
Daniel Pfeifer's avatar
Daniel Pfeifer committed
868
  if (nullptr != GetOption(groupVar)) {
869
    return std::string(GetOption(groupVar));
870
  }
871
  return componentName;
872
}