Skip to content

Commit

Permalink
Merge pull request #1 from creative-commoners/pulls/1/new-repo
Browse files Browse the repository at this point in the history
NEW Add sniffer code
  • Loading branch information
emteknetnz authored Nov 13, 2023
2 parents 512a059 + dc76ab9 commit 47f0c4d
Show file tree
Hide file tree
Showing 25 changed files with 1,165 additions and 0 deletions.
31 changes: 31 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# For more information about the properties used in
# this file, please see the EditorConfig documentation:
# http://editorconfig.org/

[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false

[*.{yml,js,json,css,scss,eslintrc,feature}]
indent_size = 2
indent_style = space

[composer.json]
indent_size = 4

# Don't perform any clean-up on thirdparty files

[thirdparty/**]
trim_trailing_whitespace = false
insert_final_newline = false

[admin/thirdparty/**]
trim_trailing_whitespace = false
insert_final_newline = false
6 changes: 6 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/.github export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
/phpunit.xml.dist export-ignore
/tests export-ignore
/.editorconfig export-ignore
11 changes: 11 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
name: CI

on:
push:
pull_request:
workflow_dispatch:

jobs:
ci:
name: CI
uses: silverstripe/gha-ci/.github/workflows/ci.yml@v1
16 changes: 16 additions & 0 deletions .github/workflows/dispatch-ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
name: Dispatch CI

on:
# At 6:30 PM UTC, only on Sunday and Monday
schedule:
- cron: '30 18 * * 0,1'

jobs:
dispatch-ci:
name: Dispatch CI
# Only run cron on the silverstripe account
if: (github.event_name == 'schedule' && github.repository_owner == 'silverstripe') || (github.event_name != 'schedule')
runs-on: ubuntu-latest
steps:
- name: Dispatch CI
uses: silverstripe/gha-dispatch-ci@v1
17 changes: 17 additions & 0 deletions .github/workflows/keepalive.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: Keepalive

on:
# At 6:30 PM UTC, on day 15 of the month
schedule:
- cron: '30 18 15 * *'
workflow_dispatch:

jobs:
keepalive:
name: Keepalive
# Only run cron on the silverstripe account
if: (github.event_name == 'schedule' && github.repository_owner == 'silverstripe') || (github.event_name != 'schedule')
runs-on: ubuntu-latest
steps:
- name: Keepalive
uses: silverstripe/gha-keepalive@v1
17 changes: 17 additions & 0 deletions .github/workflows/merge-up.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: Merge-up

on:
# At 6:30 PM UTC, only on Thursday
schedule:
- cron: '30 18 * * 4'
workflow_dispatch:

jobs:
merge-up:
name: Merge-up
# Only run cron on the silverstripe account
if: (github.event_name == 'schedule' && github.repository_owner == 'silverstripe') || (github.event_name != 'schedule')
runs-on: ubuntu-latest
steps:
- name: Merge-up
uses: silverstripe/gha-merge-up@v1
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/vendor/
/composer.lock
.phpunit.result.cache
29 changes: 29 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
BSD 3-Clause License

Copyright (c) 2023, Silverstripe Limited - www.silverstripe.com
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
51 changes: 51 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,52 @@
# Markdown PHP Codesniffer

A wrapper around [`squizlabs/PHP_CodeSniffer`](https://github.com/squizlabs/PHP_CodeSniffer) which lets you lint PHP fenced code blocks in markdown files.

## Installation

Unlike `squizlabs/PHP_CodeSniffer`, this isn't intended to be installed globally - you should install it as a dev dependency of your project.

```bash
composer require --dev silverstripe/markdown-php-codesniffer
```

## Usage

To sniff markdown files, run `mdphpcs` from the vendor bin directory:

```bash
# sniff a directory
vendor/bin/mdphpcs /path/to/docs

# sniff a specific file
vendor/bin/mdphpcs /path/to/docs/file.md
```

Most of the options available with the `phpcs` and `phpcbf` commands from `squizlabs/PHP_CodeSniffer` are available with `mdphpcs` as well.
See [PHP_CodeSniffer usage](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Usage) for more details.

### Fixing violations automatically

Some violations can be fixed automatically, and PHP_CodeSniffer will include information about those in the CLI output. To fix them, simply pass the `--fix` option to `mdphpcs`:

```bash
vendor/bin/mdphpcs /path/to/docs --fix
```

This is the equivalent of using the `phpcbf` command on regular PHP files.

### Linting other languages

`squizlabs/PHP_CodeSniffer` supports linting some languages other than PHP. Theoretically that can be done with this tool as well. You'll need to pass the language (as it's written in the markdown language hint) in with the `--linting-language` option.

```bash
vendor/bin/mdphpcs /path/to/docs --linting-language=JS
```

### Linting rules

If you have a [default configuration file](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Advanced-Usage#using-a-default-configuration-file) or explicitly pass in a standard using the `--standard` option, those rules will be used for linting - but be aware that some rules won't be appropriate for linting code blocks.

For example, the `PSR12.Files.FileHeader.HeaderPosition` rule will always fail linting, because we need to include empty lines prior to the content of the code block in the content we pass to `squizlabs/PHP_CodeSniffer` so it can correctly report the line of each violation in the original markdown file.

If you don't specify a standard and have no default configuration file, the default configuration [included in this package](./phpcs.default.xml) will be used. This configuration is based on PSR12, with some exclusions that make it appropriate for use in linting code blocks.
75 changes: 75 additions & 0 deletions bin/mdphpcs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#!/usr/bin/env php
<?php

use PHP_CodeSniffer\Exceptions\DeepExitException;
use SilverStripe\MarkdownPhpCodeSniffer\Sniffer;

// php_codesniffer autoloader (which itself includes the composer autoloader)
$autoloadCandidates = [
// running from vendor/bin (recommended)
__DIR__ . '/../squizlabs/php_codesniffer/autoload.php',
// running from package in vendor/silverstripe/markdown-php-codesniffer/bin
__DIR__ . '/../../../squizlabs/php_codesniffer/autoload.php',
// running from package itself as root (used during development of this package itself)
__DIR__ . '/../vendor/squizlabs/php_codesniffer/autoload.php',
];

$autoloaded = false;
foreach ($autoloadCandidates as $candidate) {
if (is_file($candidate)) {
require_once $candidate;
$autoloaded = true;
break;
}
}

if (!$autoloaded) {
die('Failed to include autoloader, unable to continue');
}

$args = $_SERVER['argv'];
$numArgs = count($args);
$removeArgs = [];

$usingExplicitStandard = false;
$fixing = false;

// Check for any args we need from the CLI input
for ($i = 0; $i < $numArgs; $i++) {
$arg = $args[$i];
if ($arg === '--lint-language') {
$lintLanguage = strtoupper($args[$i + 1]);
$removeArgs[] = $i;
$removeArgs[] = $i + 1;
} elseif (str_starts_with($arg, '--lint-language=')) {
$lintLanguage = strtoupper(str_replace('--lint-language=', '', $arg));
$removeArgs[] = $i;
}

if ($arg === '--fix') {
$fixing = true;
$removeArgs[] = $i;
}

if ($arg === '--standard' || str_starts_with($arg, '--standard=')) {
$usingExplicitStandard = true;
}
}

// Remove our args and reset array indices so phpcs can accurately fetch its own args
foreach ($removeArgs as $i) {
unset($_SERVER['argv'][$i]);
}
$_SERVER['argv'] = array_values($_SERVER['argv']);

// Assume PHP if no explicit language was passed in.
$lintLanguage ??= 'PHP';

try {
$sniffer = new Sniffer();
$exitCode = $sniffer->run($lintLanguage, $fixing, $usingExplicitStandard);
exit($exitCode);
} catch (DeepExitException $e) {
echo $e->getMessage();
exit($e->getCode());
}
29 changes: 29 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "silverstripe/markdown-php-codesniffer",
"description": "A wrapper around squizlabs/PHP_CodeSniffer which lets you lint PHP fenced code blocks in markdown files",
"keywords": [
"phpcs",
"standards",
"markdown",
"sniffer",
"codesniffer"
],
"license": "BSD-3-Clause",
"require": {
"php": "^8.0",
"squizlabs/php_codesniffer": "^3.7",
"league/commonmark": "^2.4"
},
"autoload": {
"psr-4": {
"SilverStripe\\MarkdownPhpCodeSniffer\\": "src/",
"SilverStripe\\MarkdownPhpCodeSniffer\\Tests\\": "tests/"
}
},
"bin": [
"bin/mdphpcs"
],
"require-dev": {
"phpunit/phpunit": "^9.6"
}
}
9 changes: 9 additions & 0 deletions phpcs.default.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<ruleset name="Markdown with PSR12">
<description>PSR12 pared down to what's sensible for code blocks in markdown</description>
<rule ref="PSR12">
<exclude name="PSR1.Files.SideEffects.FoundWithSymbols"/>
<exclude name="PSR12.Files.FileHeader.HeaderPosition"/>
<exclude name="PSR12.Files.FileHeader.SpacingAfterBlock"/>
</rule>
</ruleset>
7 changes: 7 additions & 0 deletions phpcs.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?xml version="1.0"?>
<ruleset name="PSR12">
<rule ref="PSR12"/>
<rule ref="PSR1.Files.SideEffects.FoundWithSymbols">
<exclude-pattern>tests/bootstrap\.php</exclude-pattern>
</rule>
</ruleset>
12 changes: 12 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="tests/bootstrap.php" colors="true">
<testsuites>
<testsuite name="all-except-fixing">
<directory>tests</directory>
<exclude>tests/SnifferFixTest.php</exclude>
</testsuite>
<testsuite name="fixing-only">
<file>tests/SnifferFixTest.php</file>
</testsuite>
</testsuites>
</phpunit>
46 changes: 46 additions & 0 deletions src/CodeBlock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace SilverStripe\MarkdownPhpCodeSniffer;

use PHP_CodeSniffer\Config;
use PHP_CodeSniffer\Files\DummyFile;
use PHP_CodeSniffer\Ruleset;

class CodeBlock extends DummyFile
{
public int $num;

public string $realPath;

private string $finalContent = '';

public function __construct(
Ruleset $ruleset,
Config $config,
string $content,
string $path,
string $realPath,
int $num
) {
parent::__construct($content, $ruleset, $config);

$this->path = $path;
$this->realPath = $realPath;
$this->num = $num;
}

public function cleanUp()
{
$this->finalContent = $this->content ?? '';
parent::cleanUp();
}

public function getContent(): ?string
{
if ($this->content) {
return $this->content;
}

return $this->finalContent;
}
}
Loading

0 comments on commit 47f0c4d

Please sign in to comment.