Skip to content

Commit

Permalink
🎉 init(restory): 我出生啦~
Browse files Browse the repository at this point in the history
  • Loading branch information
ClarkQAQ committed Jun 8, 2024
0 parents commit c2287df
Show file tree
Hide file tree
Showing 8 changed files with 358 additions and 0 deletions.
34 changes: 34 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# ---> Go
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib

# Test binary, built with `go test -c`
*.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out

# Dependency directories (remove the comment below to include it)
# vendor/

.buildpath
.hgignore.swp
.project
.orig
.swp
.idea/
.settings/
.vscode/
testdata/
vender/
bin/
*/.DS_Store
main
.vscode
__debug_bin
history/
release/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2024 ClarkQAQ

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
38 changes: 38 additions & 0 deletions README.en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<p align="center">
<h3 align="center">Restory</h3>
<p align="center">
Re (store + (hi) story) VSCode History Recovery Tool
</p>
</p>

> Are you using VSCode and accidentally deleted your folder? Restory can help you recover it!
### Principle

This is a very simple tool. Restory scans the file modification history files of VSCode to obtain information, and rebuilds the directory structure and file content at the location you specify.
Unfortunately, you cannot use Restory to recover files that were not modified through VSCode, as VSCode does not generate the corresponding modification history files.

### Usage

Download the binary file of `restory` for your platform from the Release page and run it.

For example, on the Linux platform:

```bash
$ curl -L -o ./restory_linux_amd64 https://github.com/ClarkQAQ/restory/releases/latest/download/restory_linux_amd64
$ chmod +x ./restory_linux_amd64
$ ./restory_linux_amd64 ~/.config/Code/User/History /tmp/code-history
```

The VSCode history folder is usually located at `~/.config/Code/User/History` on Linux and `C:\Users\[your username]\AppData\Local\Code\User\History` on Windows.

[Windows Download](https://github.com/ClarkQAQ/restory/releases/latest/download/restory_windows_amd64.exe)
[Linux Download](https://github.com/ClarkQAQ/restory/releases/latest/download/restory_linux_amd64)
[MacOS Download](https://github.com/ClarkQAQ/restory/releases/latest/download/restory_darwin_amd64)

### Finally

Please remember to back up your important files regularly! Upload them to Git timely!
This tool might help you once, but it cannot guarantee to help you every time...

---
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<p align="center">
<h3 align="center">Restory</h3>
<p align="center">
Re (store + (hi) story) VSCode 历史记录文件恢复工具
<br />
VSCode History Recovery Tool
</p>
</p>

[English README](README.en.md)

> 你在使用 VSCode,你的文件夹不小心删掉了? Restory 就能帮你恢复!
### 原理

这是一个很简单的工具. Restory 通过扫描 VSCode 的文件修改历史文件获取信息, 并在你指定的位置重建文件夹目录结构和文件内容。
很不幸的是, 你没有经过 VSCode 无法使用 Restore 恢复, 因为 VSCode 并没有产生对应的修改历史文件。


### 使用

前往 Release 下载您平台对应的 `restory` 的二进制文件然后运行即可.

例如在 Linux 平台:

```bash
$ curl -L -o ./restory_linux_amd64 https://github.com/ClarkQAQ/restory/releases/latest/download/restory_linux_amd64
$ chmod +x ./restory_linux_amd64
$ ./restory_linux_amd64 ~/.config/Code/User/History /tmp/code-history
```

VSCode 历史文件夹目录在 Linux 平台通常是 `~/.config/Code/User/History`, Windows 平台则是 `C:\Users\[你的用户名]\AppData\Local\Code\User\History`.

[Windows 下载链接](https://github.com/ClarkQAQ/restory/releases/latest/download/restory_windows_amd64.exe)
[Linux 下载链接](https://github.com/ClarkQAQ/restory/releases/latest/download/restory_linux_amd64)
[MacOS 下载链接](https://github.com/ClarkQAQ/restory/releases/latest/download/restory_darwin_amd64)

### 最后

以后请多备份自己的重要文件! 及时上传到 Git!
或许我的这个工具能帮助你一次, 但是不能保证每一次都能帮助你...
38 changes: 38 additions & 0 deletions build
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#!/bin/bash

# 定义平台和架构
PLATFORMS=("darwin/amd64" "darwin/arm64" "linux/amd64" "linux/arm64" "windows/amd64" "windows/386")

# 定义输出目录
OUTPUT_DIR="release"

# 创建输出目录
mkdir -p $OUTPUT_DIR

# 当前文件夹名称
CURRENT_DIR=$(basename $(pwd))

# 编译 main.go
for PLATFORM in "${PLATFORMS[@]}"
do
# 拆分操作系统和架构
IFS="/" read -r OS ARCH <<< "$PLATFORM"

# 设置输出文件名
OUTPUT_NAME="$CURRENT_DIR-$OS-$ARCH"
if [ "$OS" = "windows" ]; then
OUTPUT_NAME+=".exe"
fi

# 设置环境变量并编译
echo "正在编译 $OS/$ARCH..."
env GOOS=$OS GOARCH=$ARCH go build -o $OUTPUT_DIR/$OUTPUT_NAME main.go

if [ $? -ne 0 ]; then
echo "编译 $OS/$ARCH 失败!"
else
echo "编译 $OS/$ARCH 成功:$OUTPUT_DIR/$OUTPUT_NAME"
fi
done

echo "所有平台编译完成!"
7 changes: 7 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module restory

go 1.22.4

replace uw => github.com/ClarkQAQ/uw v0.0.0-20240504030941-56cb77a40d8a

require uw v0.0.0-00010101000000-000000000000
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
github.com/ClarkQAQ/uw v0.0.0-20240504030941-56cb77a40d8a h1:vsK1qfNAzCdaUNYeFl/1wh1CspCkq1tmubPTgpOdx3c=
github.com/ClarkQAQ/uw v0.0.0-20240504030941-56cb77a40d8a/go.mod h1:9+F2GXZmX6j/Ix9T/6yuk77vsW3lzYg2xmyVNLy93Iw=
177 changes: 177 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
package main

import (
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"uw/ulog"
)

type Entrie struct {
Version int `json:"version"`
Resource string `json:"resource"`
Entries EntrieObjects `json:"entries"`
}

type EntrieObject struct {
ID string `json:"id"`
Timestamp int64 `json:"timestamp"`
Source string `json:"source,omitempty"`
}

type EntrieObjects []EntrieObject

func (es EntrieObjects) Len() int {
return len(es)
}

func (es EntrieObjects) Less(i, j int) bool {
return es[i].Timestamp > es[j].Timestamp
}

func (es EntrieObjects) Swap(i, j int) {
es[i], es[j] = es[j], es[i]
}

func main() {
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "Welcome to Restory.\n")
fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
fmt.Fprintf(flag.CommandLine.Output(), "example: %s <option> <history-dir-path> <output-dir-path>\n", os.Args[0])
os.Exit(1)
}

outputHistoryFilesPtr := flag.Bool("h", false, "output history files")
debugLoggerPtr := flag.Bool("d", false, "debug logger")
flag.Parse()

if !*debugLoggerPtr {
ulog.GlobalFormat().SetLevel(ulog.GlobalFormat().GetLevel() ^ ulog.LevelDebug)
}

historyDirPath, outputDirPath := strings.TrimSpace(flag.Arg(0)), strings.TrimSpace(flag.Arg(1))
if historyDirPath == "" || outputDirPath == "" {
flag.Usage()
}

outputHistoryFiles := *outputHistoryFilesPtr

ulog.Debug("Restory:\nHistoryDir: %s\nOutputDir: %s\nOutputFiles: %t",
historyDirPath, outputDirPath, outputHistoryFiles)

if _, e := os.Stat(outputDirPath); e != nil && !errors.Is(e, os.ErrNotExist) {
ulog.Fatal("stat %s: %s", outputDirPath, e)
} else if errors.Is(e, os.ErrNotExist) {
if e := os.MkdirAll(outputDirPath, os.ModePerm); e != nil {
ulog.Fatal("create %s: %s", outputDirPath, e)
}
}

historyChunkPaths := make([]string, 0, 512)
if e := filepath.Walk(historyDirPath, func(path string, info fs.FileInfo, e error) error {
if e != nil {
return fmt.Errorf("walk at %s: %w", path, e)
}

if !info.IsDir() || path == historyDirPath {
return nil
}

historyChunkPaths = append(historyChunkPaths, path)

return nil
}); e != nil {
ulog.Fatal("walking %s: %s", historyDirPath, e)
}

ulog.Debug("chunk: %d", len(historyChunkPaths))
ps, files := ulog.Progress(10, float64(len(historyChunkPaths)), "chunk"), 0

for _, path := range historyChunkPaths {
ulog.Debug("checking: %s", path)

if e := func(historyChunkPath string) error {
entriesJsonPath := filepath.Join(historyChunkPath, "entries.json")

ulog.Debug("opening: %s", entriesJsonPath)
f, e := os.OpenFile(entriesJsonPath, os.O_RDONLY, 0)
if e != nil {
ulog.Warn("open %s: %s, skipping", entriesJsonPath, e)
return nil
}

defer f.Close()

entrie := &Entrie{}
if e := json.NewDecoder(f).Decode(&entrie); e != nil {
return fmt.Errorf("unmarshal %s: %w", entriesJsonPath, e)
}

sort.Sort(entrie.Entries)
if len(entrie.Entries) < 1 {
return nil
}
if !outputHistoryFiles {
entrie.Entries = entrie.Entries[:1]
}

targetOutputPath := filepath.Join(outputDirPath, strings.TrimPrefix(entrie.Resource, "file://"))
ulog.Debug("restoring: %s", targetOutputPath)

for i, entry := range entrie.Entries {
if e := func(i int, entry EntrieObject, targetPath string) error {
if i > 0 {
targetPath = fmt.Sprintf("%s.%d", targetPath, i)
}

if e := os.MkdirAll(filepath.Dir(targetPath), os.ModePerm); e != nil {
return fmt.Errorf("create dir %s: %w", filepath.Dir(targetPath), e)
}

tf, e := os.OpenFile(targetPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
if e != nil {
return fmt.Errorf("create %s: %w", targetPath, e)
}

defer tf.Close()

historyPath := filepath.Join(historyChunkPath, entry.ID)
hf, e := os.OpenFile(historyPath, os.O_RDONLY, 0)
if e != nil {
ulog.Warn("open %s: %s, skipping", historyPath, e)
return nil
}

defer hf.Close()

if _, e := io.Copy(tf, hf); e != nil {
return fmt.Errorf("copy %s to %s: %w", historyPath, targetPath, e)
}

ulog.Debug("copied %s to %s", historyPath, targetPath)
files++
return nil
}(i, entry, targetOutputPath); e != nil {
return fmt.Errorf("copy %s history (%d): %w", entriesJsonPath, i, e)
}
}

return nil
}(path); e != nil {
ulog.Fatal("processing %s: %s", path, e)
}

ps.Append(1, path)
}

ulog.Info("full done, saved: %d chunk (%d files) to %s, bye!",
len(historyChunkPaths), files, outputDirPath)
}

0 comments on commit c2287df

Please sign in to comment.