forked from gedex/preview-github-readme.md
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreview_github_readme.php
executable file
·88 lines (69 loc) · 2.17 KB
/
preview_github_readme.php
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
<?php
#!/usr/bin/env php
/**
* Preview your local github Readme.md.
* @author Akeda Bagus <[email protected]>
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*/
$url = 'https://api.github.com/markdown/raw';
$readme_file = null;
$base_dir = dirname( __FILE__ );
$template = file_get_contents( "{$base_dir}/preview_github_readme.html" );
$stylesheet = file_get_contents( "{$base_dir}/preview_github_readme.css" );
/**
* Lookup readme file by checking query args if in browser or
* argv if in cli. Lastly it checks common readme filenames
* in current directory.
*/
function lookup_readme_file() {
global $readme_file;
if ( 'cli' === php_sapi_name() && isset( $argv[1] ) ) {
if ( file_exists( $argv[1] ) ) {
$readme_file = $argv[1];
return;
}
}
else if ( isset( $_GET['file'] ) && !empty( $_GET['file'] ) ) {
$readme_file = $_GET['file'];
if ( file_exists($readme_file) ) {
return;
}
}
$readme_candidates = array( 'README.md', 'Readme.md', 'readme.md' );
foreach ( $readme_candidates as $readme ) {
if ( file_exists($readme) ) {
$readme_file = $readme;
return;
}
}
$readme_file = null;
}
lookup_readme_file();
function cli_usage() {
global $argv;
echo "Usage: preview_github_readme [README.md file]\n";
exit(1);
die;
}
if ( !$readme_file ) {
if ( 'cli' === php_sapi_name() )
cli_usage();
trigger_error("No README.md file found!", E_USER_ERROR);
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($readme_file));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: text/plain'));
$response = curl_exec($ch);
curl_close($ch);
ob_start(function($buffer) {
global $template, $response, $readme_file, $stylesheet;
$tpl = file_get_contents($readme_file);
$buffer = str_replace("%stylesheet%", "<style>{$stylesheet}</style>", $buffer);
return (str_replace("%markdown%", $response, $buffer));
});
echo $template;
ob_end_flush();