All files / owid-grapher/gitCms GitCmsServer.ts

96.07% Statements 220/229
66.67% Branches 22/33
100% Functions 13/13
96.07% Lines 220/229

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 3091x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 10x 10x 1x 1x 12x 12x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x 1x 1x 3x 3x         3x 3x 3x 3x 3x 3x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x     1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 2x 1x 1x                                                                                                                                                                      
import { Router, Request, Response, RequestHandler } from "express"
import {
    GIT_DEFAULT_USERNAME,
    GIT_DEFAULT_EMAIL,
} from "../settings/serverSettings"
import simpleGit, { SimpleGit } from "simple-git"
import {
    writeFile,
    existsSync,
    readFile,
    unlink,
    readFileSync,
    mkdirSync,
} from "fs-extra"
import {
    WriteRequest,
    ReadRequest,
    DeleteRequest,
    GlobRequest,
    GitPullResponse,
    GitCmsGlobResponse,
    GitCmsResponse,
    GitCmsReadResponse,
    GIT_CMS_GLOB_ROUTE,
    GIT_CMS_READ_ROUTE,
    GIT_CMS_WRITE_ROUTE,
    GIT_CMS_DELETE_ROUTE,
    GIT_CMS_PULL_ROUTE,
} from "./GitCmsConstants"
import { sync } from "glob"
import { logErrorAndMaybeSendToSlack } from "../serverUtils/slackLog"
 
// todo: cleanup typings
interface ResponseWithUserInfo extends Response {
    locals: { user: any; session: any }
}
 
interface GitCmsServerOptions {
    baseDir: string
    shouldAutoPush?: boolean
}
 
export class GitCmsServer {
    private _options: GitCmsServerOptions
    verbose = true // I made this public so you can test quietly
 
    constructor(options: GitCmsServerOptions) {
        this._options = options
    }
 
    // todo: we should probably use the 'path' lib and standardize things for cross plat
    private get baseDir() {
        return this.options.baseDir + "/"
    }
 
    private get options() {
        return this._options
    }
 
    private _git?: SimpleGit
    private get git() {
        if (!this._git)
            this._git = simpleGit({
                baseDir: this.baseDir,
                binary: "git",
                maxConcurrentProcesses: 1,
                // Needed since git won't let you commit if there's no user name config present (i.e. CI), even if you always
                // specify `author=` in every command. See https://stackoverflow.com/q/29685337/10670163 for example.
                config: [
                    `user.name='${GIT_DEFAULT_USERNAME}'`,
                    `user.email='${GIT_DEFAULT_EMAIL}'`,
                ],
            })
        return this._git
    }
 
    async createDirAndInitIfNeeded() {
        const { baseDir } = this
        if (!existsSync(baseDir)) mkdirSync(baseDir)
        await this.git.init()
 
        return this
    }
 
    private async commitFile(
        filename: string,
        commitMsg: string,
        authorName: string,
        authorEmail: string
    ) {
        await this.git.add(filename)
        return await this.git.commit(commitMsg, filename, {
            "--author": `${authorName} <${authorEmail}>`,
        })
    }
 
    private async autopush() {
        if (this.options.shouldAutoPush) this.git.push()
    }
 
    private async pullCommand(verbose: boolean | undefined = undefined) {
        try {
            const res = await this.git.pull()
            return {
                success: true,
                stdout: JSON.stringify(res.summary, null, 2),
            } as GitPullResponse
        } catch (error) {
            const err = error as Error
            if (verbose ?? this.verbose) console.log(err)
            return { success: false, error: err.toString() }
        }
    }
 
    // Pull changes before making changes. However, only pull if an upstream branch is set up.
    private async autopull() {
        const res = await this.pullCommand(false)
 
        if (!res.success) {
            const err = res.error as string | undefined
            if (
                err?.includes(
                    "There is no tracking information for the current branch." // local-only branch
                ) ||
                err?.includes("You are not currently on a branch.") // detached HEAD
            )
                return { success: true }
        }
        return res
    }
 
    private async readFileCommand(
        filepath: string
    ): Promise<GitCmsReadResponse> {
        try {
            ensureNoParentLinksInFilePath(filepath)
 
            const absolutePath = this.baseDir + filepath
            const exists = existsSync(absolutePath)
            if (!exists) throw new Error(`File '${filepath}' not found`)
            const content = await readFile(absolutePath, "utf8")
            return { success: true, content }
        } catch (error) {
            const err = error as Error
            if (this.verbose) console.log(err)
            return {
                success: false,
                error: err.toString(),
                content: "",
            }
        }
    }
 
    private async globCommand(
        globStr: string,
        folder: string
    ): Promise<GitCmsGlobResponse> {
        const query = globStr.replace(/[^a-zA-Z\*]/, "")
        const cwd = this.baseDir + folder
        const results = sync(query, {
            cwd,
        })
 
        const files = results.map((filename) => {
            return {
                filename,
                content: readFileSync(cwd + "/" + filename, "utf8"),
            }
        })
 
        return { success: true, files }
    }
 
    private async deleteFileCommand(
        rawFilepath: string,
        authorName = GIT_DEFAULT_USERNAME,
        authorEmail = GIT_DEFAULT_EMAIL
    ): Promise<GitCmsResponse> {
        const filepath = rawFilepath.replace(/\~/g, "/")
        try {
            ensureNoParentLinksInFilePath(filepath)
 
            const absolutePath = this.baseDir + filepath
            await unlink(absolutePath)
 
            // Do a pull _after_ the file delete. This ensures that, if we intend to delete
            // a file that has been changed on the server, we'll end up with an intentional failure.
            const pull = await this.autopull()
            if (!pull.success) throw pull.error
 
            await this.commitFile(
                filepath,
                `Deleted ${filepath}`,
                authorName,
                authorEmail
            )
 
            await this.autopush()
            return { success: true }
        } catch (error) {
            const err = error as Error
            logErrorAndMaybeSendToSlack(err)
            return { success: false, error: err.toString() }
        }
    }
 
    private async writeFileCommand(
        filename: string,
        content: string,
        authorName = GIT_DEFAULT_USERNAME,
        authorEmail = GIT_DEFAULT_EMAIL,
        commitMessage?: string
    ): Promise<GitCmsResponse> {
        try {
            ensureNoParentLinksInFilePath(filename)
 
            const absolutePath = this.baseDir + filename
            await writeFile(absolutePath, content, "utf8")
 
            // Do a pull _after_ the write. This ensures that, if we intend to overwrite a file
            // that has been changed on the server, we'll end up with an intentional merge conflict.
            await this.autopull()
            const pull = await this.autopull()
            if (!pull.success) throw pull.error
 
            const commitMsg = commitMessage
                ? commitMessage
                : existsSync(absolutePath)
                ? `Updating ${filename}`
                : `Adding ${filename}`
 
            await this.commitFile(filename, commitMsg, authorName, authorEmail)
            await this.autopush()
            return { success: true }
        } catch (error) {
            const err = error as Error
            logErrorAndMaybeSendToSlack(err)
            return { success: false, error: err.toString() }
        }
    }
 
    addToRouter(app: Router) {
        const routes: { [route: string]: RequestHandler } = {}
 
        routes[GIT_CMS_PULL_ROUTE] = async (
            req: Request,
            res: ResponseWithUserInfo
        ) => res.send(await this.pullCommand()) // Pull latest from github
 
        routes[GIT_CMS_GLOB_ROUTE] = async (
            req: Request,
            res: ResponseWithUserInfo
        ) => {
            // Get multiple file contents
            const request = req.body as GlobRequest
            res.send(await this.globCommand(request.glob, request.folder))
        }
 
        routes[GIT_CMS_READ_ROUTE] = async (
            req: Request,
            res: ResponseWithUserInfo
        ) => {
            const request = req.body as ReadRequest
            res.send(await this.readFileCommand(request.filepath))
        }
 
        routes[GIT_CMS_WRITE_ROUTE] = async (
            req: Request,
            res: ResponseWithUserInfo
        ) => {
            // Update/create file, commit, and push(unless on local dev brach)
            const request = req.body as WriteRequest
            const { filepath, content, commitMessage } = request
            res.send(
                await this.writeFileCommand(
                    filepath,
                    content,
                    res.locals.user?.fullName, // todo: these are specific to our admin app
                    res.locals.user?.email,
                    commitMessage
                )
            )
        }
 
        routes[GIT_CMS_DELETE_ROUTE] = async (
            req: Request,
            res: ResponseWithUserInfo
        ) => {
            // Delete file, commit, and and push(unless on local dev brach)
            const request = req.body as DeleteRequest
            res.send(
                await this.deleteFileCommand(
                    request.filepath,
                    res.locals.user?.fullName,
                    res.locals.user?.email
                )
            )
        }
 
        // Note: these are all POST routes, because we never want to cache any of them (even the 2 read ops)
        Object.keys(routes).forEach((route) => app.post(route, routes[route]))
    }
}
 
const ensureNoParentLinksInFilePath = (filename: string) => {
    if (filename.includes(".."))
        throw new Error(`Invalid filepath: ${filename}`)
}