1+ import path = require( 'path' ) ;
12import * as vscode from 'vscode' ;
2-
3+ const fs = require ( 'fs' ) ;
4+ import { exec } from 'child_process' ;
5+ import { rejects } from 'assert' ;
36export function getNow ( ) {
47 let dateTime
58 let yy = new Date ( ) . getFullYear ( )
@@ -18,3 +21,70 @@ export function getNow() {
1821export function getConfig < T = any > ( key : string ) {
1922 return vscode . workspace . getConfiguration ( ) . get < T > ( `code-auto-commit.${ key } ` ) ;
2023}
24+
25+ const errorType : {
26+ [ propName : string ] : string ;
27+ }
28+ = {
29+ notRepository : "fatal: not a git repository (or any of the parent directories): .git" ,
30+ }
31+
32+ export const checkIsRepository = async ( path :string ) => {
33+ const cmd = `cd ${ path } && git log`
34+ let res :boolean ;
35+ try {
36+ const msg = await runCommand ( cmd )
37+ res = true
38+ } catch ( e ) {
39+ console . log ( e )
40+ res = false
41+ }
42+ return res
43+ }
44+
45+ export const throwErrorType = function ( errMsg : string ) {
46+ for ( let key in errorType ) {
47+ if ( errMsg . includes ( errorType [ key ] ) ) {
48+ return key
49+ }
50+ }
51+ return errMsg
52+ }
53+ export const checkPathSafe = async ( path ?:readonly vscode . WorkspaceFolder [ ] ) => {
54+ if ( ! path ) {
55+ return '不是合法目录'
56+ }
57+ let isRepository = await checkIsRepository ( path [ 0 ] . uri . fsPath )
58+ if ( ! isRepository ) {
59+ return '不是一个git管理项目'
60+ }
61+ return null
62+ }
63+ export const runCommand = ( cmd :string ) => {
64+ return new Promise ( ( resolve , reject ) => {
65+ cmd = cmd + ' && git diff'
66+ let res = ''
67+ exec ( cmd , ( err , stdout ) => {
68+ if ( err ) {
69+ reject ( err . message ) ;
70+ } else {
71+ resolve ( stdout )
72+ }
73+ } )
74+ } )
75+ }
76+ /**
77+ * 从某个HTML文件读取能被Webview加载的HTML内容
78+ * @param {string } context 上下文
79+ * @param {string } templatePath 相对于插件根目录的html文件相对路径
80+ */
81+ function getWebViewContent ( context :vscode . ExtensionContext , templatePath :string ) {
82+ const resourcePath = path . join ( context . extensionPath , templatePath ) ;
83+ const dirPath = path . dirname ( resourcePath ) ;
84+ let html :string = fs . readFileSync ( resourcePath , 'utf-8' ) ;
85+ // vscode不支持直接加载本地资源,需要替换成其专有路径格式,这里只是简单的将样式和JS的路径替换
86+ html = html . replace ( / ( < l i n k .+ ?h r e f = " | < s c r i p t .+ ?s r c = " | < i m g .+ ?s r c = " ) ( .+ ?) " / g, ( m :string , $1 :string , $2 :string ) => {
87+ return $1 + vscode . Uri . file ( path . resolve ( dirPath , $2 ) ) . with ( { scheme : 'vscode-resource' } ) . toString ( ) + '"' ;
88+ } ) ;
89+ return html ;
90+ }
0 commit comments