Skip to content

Commit

Permalink
feat(#35): config to prefer home tilde
Browse files Browse the repository at this point in the history
  • Loading branch information
jannis-baum committed Jul 13, 2024
1 parent 634b3fb commit 2636b0d
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 12 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ following optional keys:
files will be displayed as monospaced text with code highlighting if
available. Default Markdown extensions are `['markdown', 'md', 'mdown',
'mdwn', 'mkd', 'mkdn']`
- **`"preferHomeTilde"`**\
Prefer using `~` as a placeholder for your home directory in URLs as well as
the `compoments` for `"pageTitle"` (default is `true`)

## Installation

Expand Down
16 changes: 13 additions & 3 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,25 @@ import { router as healthRouter } from './routes/health.js';
import { router as staticRouter } from './routes/static.js';
import { router as viewerRouter } from './routes/viewer.js';
import { setupSockets } from './sockets.js';
import { pathToURL, urlToPath } from './utils/path.js';
import { pathToURL, preferredPath, urlToPath } from './utils/path.js';
import { existsSync } from 'fs';
import { homedir } from 'os';

const app = express();
app.use(express.json());
app.use((req, res, next) => {
res.locals.filepath = urlToPath(req.path);
next();
});
if (config.preferHomeTilde) {
app.use((req, res, next) => {
if (res.locals.filepath.startsWith(homedir()) && !req.path.includes('~')) {
res.redirect(req.path.replace(homedir(), '/~'));
} else {
next();
}
});
}
app.use('/static', staticRouter);
app.use('/health', healthRouter);
app.use('/viewer', viewerRouter);
Expand Down Expand Up @@ -47,8 +57,8 @@ const openArgs = () => {
console.log(`File not found: ${path}`);
continue;
}
const absolute = presolve(path);
const url = `${address}${pathToURL(absolute)}`;
const target = preferredPath(presolve(path));
const url = `${address}${pathToURL(target)}`;
open(url);
}
};
Expand Down
2 changes: 2 additions & 0 deletions src/parser/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@ type Config = {
pageTitle?: string;
mdExtensions: string[];
timeout: number;
preferHomeTilde: boolean;
};

const defaultConfig: Config = {
port: 31622,
mdExtensions: ['markdown', 'md', 'mdown', 'mdwn', 'mkd', 'mkdn'],
timeout: 10000,
preferHomeTilde: true,
};

const envConfigs: [string, keyof Config][] = [
Expand Down
6 changes: 3 additions & 3 deletions src/routes/viewer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ import { Request, Response, Router } from 'express';

import { messageClientsAt } from '../app.js';
import config from '../parser/config.js';
import { pathToURL, pcomponents, pmime } from '../utils/path.js';
import { absPath, pathToURL, pcomponents, pmime, preferredPath } from '../utils/path.js';
import { renderDirectory, renderTextFile } from '../parser/parser.js';

export const router = Router();

const liveContent = new Map<string, string>();

const pageTitle = (path: string) => {
const comps = pcomponents(path);
const comps = pcomponents(preferredPath(path));
if (config.pageTitle) {
return eval(`
const components = ${JSON.stringify(comps)};
Expand Down Expand Up @@ -74,7 +74,7 @@ router.get(/.*/, async (req: Request, res: Response) => {
</body>
<script>
window.VIV_PORT = "${config.port}";
window.VIV_PATH = "${req.path}";
window.VIV_PATH = "${absPath(req.path)}";
</script>
<script type="text/javascript" src="/static/client.js"></script>
</html>
Expand Down
18 changes: 12 additions & 6 deletions src/utils/path.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { execSync } from 'child_process';
import { homedir } from 'os';
import { basename as pbasename, dirname as pdirname, parse as pparse } from 'path';
import config from '../parser/config.js';

export const pmime = (path: string) => execSync(`file --mime-type -b '${path}'`).toString().trim();

Expand All @@ -9,7 +10,7 @@ export const pcomponents = (path: string) => {
const components = new Array<string>();
// directory
let dir = parsed.dir;
while (dir !== '/' && dir !== '') {
while (dir !== '/' && dir !== '.') {
components.unshift(pbasename(dir));
dir = pdirname(dir);
}
Expand All @@ -20,12 +21,17 @@ export const pcomponents = (path: string) => {
return components;
};

export const absPath = (path: string) => path.replace(/^\/~/, homedir()).replace(/\/+$/, '');

export const urlToPath = (url: string) => {
const path = decodeURIComponent(url.replace(/^\/(viewer|health)/, ''))
.replace(/^\/~/, homedir())
.replace(/\/+$/, '');
const path = absPath(decodeURIComponent(url.replace(/^\/(viewer|health)/, '')));
return path === '' ? '/' : path;
};

export const pathToURL = (path: string, route: string = 'viewer') =>
`/${route}${encodeURIComponent(path).replaceAll('%2F', '/')}`;
export const pathToURL = (path: string, route: string = 'viewer') => {
const withoutPrefix = path.startsWith('/') ? path.slice(1) : path;
return `/${route}/${encodeURIComponent(withoutPrefix).replaceAll('%2F', '/')}`;
};

export const preferredPath = (path: string): string =>
config.preferHomeTilde && path.startsWith(homedir()) ? path.replace(homedir(), '~') : path;

0 comments on commit 2636b0d

Please sign in to comment.