Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a default config #14

Merged
merged 1 commit into from
Jan 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,6 @@ dist
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

# Linkspector
.linkspector.yml
22 changes: 16 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ To check hyperlinks in your markup language files, follow these steps:

1. Navigate to the directory containing the files you want to check.

1. Create a [configuration](#configuration) file called `.linkspector.yml`. By default, Linkspector looks for a configuration file named `.linkspector.yml` in the current directory. If you have a custom configuration file or want to specify its path, you can use the `-c` or `--config` option.
1. (**Optional**) Create a [configuration](#configuration) file called `.linkspector.yml`. By default, Linkspector looks for a configuration file named `.linkspector.yml` in the current directory. If you have a custom configuration file or want to specify its path, you can use the `-c` or `--config` option.

1. Use the `linkspector check` command to initiate the hyperlink check. For example:

Expand All @@ -51,17 +51,27 @@ To check hyperlinks in your markup language files, follow these steps:
linkspector check -c /path/to/custom-config.yml
```

1. Linkspector will start checking the hyperlinks in your files based on the configuration provided in the configuration file. It will display the results in your terminal.
1. Linkspector starts checking the hyperlinks in your files based on the configuration provided in the configuration file or using the default configuration. It then displays the results in your terminal.

1. After the check is complete, Linkspector will provide a summary of the results. If any dead links are found, they will be listed in the terminal, along with their status codes and error messages.
1. After the check is complete, Linkspector provides a summary of the results. If any dead links are found, they are listed in the terminal, along with their status codes and error messages.

1. If no dead links are found, Linkspector will display a success message, indicating that all links are working.
1. If no dead links are found, Linkspector displays a success message, indicating that all links are working.

## Configuration

The configuration file allows you to customize the behavior of Linkspector according to your specific needs. You can adjust the file paths, URL patterns, and other settings to ensure accurate and relevant link checking.
Linkspector uses a configuration file named `.linkspector.yml` to customize its behavior. If this file is not found in the current directory when the program is run, Linkspector displays a message saying "Configuration file not found. Using default configuration." and uses a default configuration.

Use the following configuration options:
### Default Configuration

The default configuration is as follows:

```yaml
dirs:
- .
useGitIgnore: true
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 , after making the issue I thought that maybe useGitIgnore would be a good default too.

```

Following are the available configuration options:

### Files to Check
The `files` section specifies the Markdown files that Linkspector should check for broken links. You can add the file paths you want to include in this list. For example:
Expand Down
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { linkspector } from "./linkspector.js";

// Define the program and its options
program
.version("0.2.2")
.version("0.2.3")
.description("🔍 Uncover broken links in your content.")
.command("check")
.description("Check hyperlinks based on the configuration file.")
Expand Down
85 changes: 51 additions & 34 deletions linkspector.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { execSync } from "child_process";
import { readFileSync, existsSync } from "fs";
import { readFileSync } from "fs";
import path from "path";
import yaml from "js-yaml";
import { validateConfig } from "./lib/validate-config.js";
Expand All @@ -21,72 +21,89 @@ function isGitInstalled() {
}

export async function* linkspector(configFile) {
// Check if the config file exists
if (!existsSync(configFile)) {
throw new Error(
"Configuration file not found. Create a '.linkspector.yml' file at the root of your project or use the '--config' option to specify another configuration file."
);
}

// Read and validate the config file
const configContent = readFileSync(configFile, "utf-8");
//Use default configuration if no config file is specified
let config = {};
let defaultConfig = {
dirs: ["."],
useGitIgnore: true,
};

// Check if the YAML content is empty
if (!configContent.trim()) {
throw new Error("The configuration file is empty.");
}
try {
let configContent = readFileSync(configFile, "utf8");
// parse configFile
// Check if the YAML content is empty
if (!configContent.trim()) {
throw new Error("The configuration file is empty.");
}

// Parse the YAML content
const config = yaml.load(configContent);
// Parse the YAML content
config = yaml.load(configContent);

// Check if the parsed YAML object is null or lacks properties
if (config === null || Object.keys(config).length === 0) {
throw new Error("Failed to parse the YAML content.");
}
// Check if the parsed YAML object is null or lacks properties
if (config === null || Object.keys(config).length === 0) {
throw new Error("Failed to parse the YAML content.");
}

try {
const isValid = await validateConfig(config);
if (!isValid) {
console.error("Validation failed!")
try {
const isValid = await validateConfig(config);
if (!isValid) {
console.error("Validation failed!");
process.exit(1);
}
} catch (error) {
console.error(`💥 Error: Please check your configuration file.`);
process.exit(1);
}
} catch (error) {
console.error(`💥 Error: Please check your configuration file.`)
process.exit(1);
} catch (err) {
if (err.code === "ENOENT") {
console.log("Configuration file not found. Using default configuration.");
config = defaultConfig;
} else {
throw new Error(err);
}
}

// Prepare the list of files to check
let filesToCheck = prepareFilesList(config);

// Convert all paths in filesToCheck to relative paths
filesToCheck = filesToCheck.map(file => path.relative(process.cwd(), file));
filesToCheck = filesToCheck.map((file) => path.relative(process.cwd(), file));

// Check if only modified files should be checked
if (config.modifiedFilesOnly) {
// Check if git is installed
if (!isGitInstalled()) {
console.error("Error: Git is not installed or not found in the system path.");
console.error(
"Error: Git is not installed or not found in the system path."
);
process.exit(1);
}

// Get the list of modified files from the last git commit
const modifiedFiles = execSync("git diff --name-only HEAD HEAD~1", { encoding: "utf8" }).split("\n");
const modifiedFiles = execSync("git diff --name-only HEAD HEAD~1", {
encoding: "utf8",
}).split("\n");

// Filter out files that are not in the list of files to check or do not have the correct extension
const modifiedFilesToCheck = modifiedFiles.filter(file => {
const modifiedFilesToCheck = modifiedFiles.filter((file) => {
const fileExtension = path.extname(file).substring(1).toLowerCase();
return filesToCheck.includes(file) && (config.fileExtensions || ["md"]).includes(fileExtension);
return (
filesToCheck.includes(file) &&
(config.fileExtensions || ["md"]).includes(fileExtension)
);
});

// If no modified files are in the list of files to check, exit with a message
if (modifiedFilesToCheck.length === 0) {
console.log("Skipped link checking. Modified files are not specified in the configuration.");
console.log(
"Skipped link checking. Modified files are not specified in the configuration."
);
process.exit(0);
}

// Otherwise, only check the modified files
filesToCheck = modifiedFilesToCheck;
console.log(filesToCheck)
console.log(filesToCheck);
}

// Initialize an array to store link status objects
Expand Down
Loading