Task 122: .D File format

Task 122: .D File format

  1. Properties of the .D file format intrinsic to its file system:
  • Target: The object file (e.g., main.o) that depends on the listed files.
  • Dependencies: The list of source and header files (e.g., main.c defs.h) that the target depends on, which are file system paths.
  1. Two direct download links for files of format .D:

Unfortunately, I could not find direct download links for .D (dependency) files, as they are typically generated during builds and not hosted for download. Here is an example content of a .D file for reference:

main.o: main.c defs.h

  1. Ghost blog embedded HTML JavaScript for drag and drop .D file to dump properties:
Drag and drop .D file here
  1. Python class for .D file:
class DFileHandler:
    def __init__(self, filename):
        self.filename = filename
        self.target = None
        self.dependencies = []

    def read(self):
        with open(self.filename, 'r') as f:
            content = f.read().trim()
            parts = content.split(':')
            if len(parts) >= 2:
                self.target = parts[0].strip()
                self.dependencies = [d.strip() for d in parts[1].split() if d.strip()]
            else:
                raise ValueError("Invalid .D file format")

    def print_properties(self):
        if self.target is None:
            print("No properties loaded.")
            return
        print(f"Target: {self.target}")
        print("Dependencies:")
        for dep in self.dependencies:
            print(f"  - {dep}")

    def write(self, target, dependencies):
        content = f"{target}: {' '.join(dependencies)}\n"
        with open(self.filename, 'w') as f:
            f.write(content)

# Example usage
if __name__ == "__main__":
    handler = DFileHandler("example.d")
    handler.read()
    handler.print_properties()
    # To write
    handler.write("main.o", ["main.c", "defs.h"])
  1. Java class for .D file:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class DFileHandler {
    private String filename;
    private String target;
    private List<String> dependencies = new ArrayList<>();

    public DFileHandler(String filename) {
        this.filename = filename;
    }

    public void read() throws IOException {
        try (BufferedReader br = new FileReader(filename)) {
            String content = br.readLine().trim();
            String[] parts = content.split(":");
            if (parts.length >= 2) {
                target = parts[0].trim();
                String depsStr = parts[1].trim();
                for (String dep : depsStr.split("\\s+")) {
                    if (!dep.isEmpty()) {
                        dependencies.add(dep);
                    }
                }
            } else {
                throw new IOException("Invalid .D file format");
            }
        }
    }

    public void printProperties() {
        if (target == null) {
            System.out.println("No properties loaded.");
            return;
        }
        System.out.println("Target: " + target);
        System.out.println("Dependencies:");
        for (String dep : dependencies) {
            System.out.println("  - " + dep);
        }
    }

    public void write(String target, List<String> dependencies) throws IOException {
        String content = target + ": " + String.join(" ", dependencies) + "\n";
        try (FileWriter fw = new FileWriter(filename)) {
            fw.write(content);
        }
    }

    // Example usage
    public static void main(String[] args) throws IOException {
        DFileHandler handler = new DFileHandler("example.d");
        handler.read();
        handler.printProperties();
        // To write
        List<String> deps = new ArrayList<>();
        deps.add("main.c");
        deps.add("defs.h");
        handler.write("main.o", deps);
    }
}
  1. JavaScript class for .D file:
class DFileHandler {
  constructor(filename) {
    this.filename = filename;
    this.target = null;
    this.dependencies = [];
  }

  async read() {
    // Assuming node.js with fs module
    const fs = require('fs');
    return new Promise((resolve, reject) => {
      fs.readFile(this.filename, 'utf8', (err, content) => {
        if (err) return reject(err);
        content = content.trim();
        const parts = content.split(':');
        if (parts.length >= 2) {
          this.target = parts[0].trim();
          this.dependencies = parts[1].trim().split(/\s+/).filter(d => d);
          resolve();
        } else {
          reject(new Error('Invalid .D file format'));
        }
      });
    });
  }

  printProperties() {
    if (this.target === null) {
      console.log('No properties loaded.');
      return;
    }
    console.log(`Target: ${this.target}`);
    console.log('Dependencies:');
    this.dependencies.forEach(dep => console.log(`  - ${dep}`));
  }

  async write(target, dependencies) {
    const fs = require('fs');
    const content = `${target}: ${dependencies.join(' ')}\n`;
    return new Promise((resolve, reject) => {
      fs.writeFile(this.filename, content, err => {
        if (err) return reject(err);
        resolve();
      });
    });
  }
}

// Example usage
(async () => {
  const handler = new DFileHandler('example.d');
  try {
    await handler.read();
    handler.printProperties();
    // To write
    await handler.write('main.o', ['main.c', 'defs.h']);
  } catch (err) {
    console.error(err);
  }
})();
  1. C class for .D file:

Note: C does not have classes natively, so using a struct with functions.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
  char *filename;
  char *target;
  char **dependencies;
  int dep_count;
} DFileHandler;

DFileHandler *dfile_create(const char *filename) {
  DFileHandler *handler = malloc(sizeof(DFileHandler));
  handler->filename = strdup(filename);
  handler->target = NULL;
  handler->dependencies = NULL;
  handler->dep_count = 0;
  return handler;
}

void dfile_destroy(DFileHandler *handler) {
  if (handler->target) free(handler->target);
  for (int i = 0; i < handler->dep_count; i++) {
    free(handler->dependencies[i]);
  }
  if (handler->dependencies) free(handler->dependencies);
  free(handler->filename);
  free(handler);
}

int dfile_read(DFileHandler *handler) {
  FILE *f = fopen(handler->filename, "r");
  if (!f) return 1;
  char content[1024]; // Assume small file
  if (fgets(content, sizeof(content), f) == NULL) {
    fclose(f);
    return 1;
  }
  fclose(f);
  char *colon = strchr(content, ':');
  if (!colon) return 1;
  *colon = '\0';
  handler->target = strdup(content);
  char *deps_str = colon + 1;
  char *dep = strtok(deps_str, " \n");
  while (dep) {
    handler->dependencies = realloc(handler->dependencies, (handler->dep_count + 1) * sizeof(char*));
    handler->dependencies[handler->dep_count++] = strdup(dep);
    dep = strtok(NULL, " \n");
  }
  return 0;
}

void dfile_print_properties(DFileHandler *handler) {
  if (handler->target == NULL) {
    printf("No properties loaded.\n");
    return;
  }
  printf("Target: %s\n", handler->target);
  printf("Dependencies:\n");
  for (int i = 0; i < handler->dep_count; i++) {
    printf("  - %s\n", handler->dependencies[i]);
  }
}

int dfile_write(DFileHandler *handler, const char *target, const char **dependencies, int dep_count) {
  FILE *f = fopen(handler->filename, "w");
  if (!f) return 1;
  fprintf(f, "%s:", target);
  for (int i = 0; i < dep_count; i++) {
    fprintf(f, " %s", dependencies[i]);
  }
  fprintf(f, "\n");
  fclose(f);
  return 0;
}

// Example usage
int main() {
  DFileHandler *handler = dfile_create("example.d");
  if (dfile_read(handler) == 0) {
    dfile_print_properties(handler);
  } else {
    printf("Error reading file.\n");
  }
  // To write
  const char *deps[] = {"main.c", "defs.h"};
  dfile_write(handler, "main.o", deps, 2);
  dfile_destroy(handler);
  return 0;
}