Skip to content

Commit

Permalink
refactor: replace dajs with date-fns and remove got
Browse files Browse the repository at this point in the history
  • Loading branch information
muuvmuuv committed Jan 21, 2025
1 parent 64e8006 commit 1bd6d23
Show file tree
Hide file tree
Showing 10 changed files with 81 additions and 289 deletions.
85 changes: 4 additions & 81 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 0 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,6 @@
},
"dependencies": {
"date-fns": "^4.1.0",
"dayjs": "^1.11.13",
"got": "^14.4.5",
"is-online": "^11.0.0",
"suncalc": "^1.8.0"
},
Expand Down Expand Up @@ -77,10 +75,6 @@
{
"command": "sundial.disableExtension",
"title": "Sundial: Disable extension"
},
{
"command": "sundial.pauseUntilNextCircle",
"title": "Sundial: Pause until next circle"
}
],
"keybindings": [
Expand Down Expand Up @@ -146,11 +140,6 @@
"type": "number",
"default": 5,
"description": "Set in which interval Sundial should check the time. (in minutes)"
},
"sundial.debug": {
"type": "number",
"default": 1,
"description": "Set debug level: silent = 0, info = 1, error = 2, debug = 3"
}
}
}
Expand Down
12 changes: 3 additions & 9 deletions src/editor.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
import dayjs from "dayjs"
import customParseFormat from "dayjs/plugin/customParseFormat"
import { type WorkspaceConfiguration, window, workspace } from "vscode"

import { getLogger } from "./logger.js"
import { log } from "./logger.js"
import type { SundialConfiguration } from "./sundial.js"

const log = getLogger("editor")

dayjs.extend(customParseFormat)

export function getConfig() {
return {
sundial: workspace.getConfiguration("sundial") as SundialConfiguration,
Expand All @@ -21,7 +15,7 @@ export function applySettings(settings: WorkspaceConfiguration): void {
return // no settings, nothing to do
}

log.debug("Changing settings to:", JSON.stringify(settings, undefined, 2))
// log.debug("NEW", JSON.stringify(settings, undefined, 2))

const workspaceSettings = workspace.getConfiguration()

Expand All @@ -47,7 +41,7 @@ export enum TimeName {
}

export function changeThemeTo(newTheme: string): void {
log.debug("Changing theme to:", newTheme)
log.debug("Changing theme to", newTheme)
const { workbench } = getConfig()
if (newTheme !== workbench.colorTheme) {
workbench.update("colorTheme", newTheme, true)
Expand Down
3 changes: 0 additions & 3 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,6 @@ export function activate(context: ExtensionContext): void {

commands.registerCommand("sundial.enableExtension", () => sundial.enableExtension())
commands.registerCommand("sundial.disableExtension", () => sundial.disableExtension())
commands.registerCommand("sundial.pauseUntilNextCircle", () =>
sundial.pauseUntilNextCircle(),
)
}

export function deactivate(): void {
Expand Down
44 changes: 5 additions & 39 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,17 @@
import { window } from "vscode"

export enum LogLevel {
enum LogLevel {
Silent = 0,
Info = 1,
Error = 2,
Debug = 3,
}

type AllowedTypes = string | number | boolean | object
type AllowedTypes = string | number | boolean | Date

export const loggers: Logger[] = []
export const outputChannel = window.createOutputChannel("Sundial")

export function setLogLevelAll(level: LogLevel): void {
for (const l of loggers) {
l.logLevel = level
}
}

class Logger {
readonly name: string
logLevel: LogLevel

constructor(name: string, logLevel = LogLevel.Info) {
this.name = name
this.logLevel = logLevel
}

info(...messages: AllowedTypes[]) {
this.log(messages, LogLevel.Info)
}
Expand All @@ -40,28 +25,9 @@ class Logger {
}

private log(messages: AllowedTypes[], level: LogLevel = LogLevel.Silent) {
if (this.logLevel < level) {
return
}
outputChannel.appendLine(this.buildLogString(level, messages))
}

private buildLogString(logLevel: LogLevel, messages: AllowedTypes[]): string {
const template: string[] = []
template.push(`[${LogLevel[logLevel].toUpperCase()}]`, `(Sundial:${this.name})`, "=>")
for (const message of messages) {
template.push(message.toString())
}
return template.join(" ")
const logMessage = `[${LogLevel[level].toUpperCase()}] ${messages.join(" ")}`
outputChannel.appendLine(logMessage)
}
}

export function getLogger(name: string): Logger {
const logger = loggers.find((l) => l.name === name)
if (logger) {
return logger
}
const newLogger = new Logger(name)
loggers.push(newLogger)
return newLogger
}
export const log = new Logger()
52 changes: 22 additions & 30 deletions src/sensors/autolocale.ts
Original file line number Diff line number Diff line change
@@ -1,77 +1,69 @@
import dayjs from "dayjs"
import got from "got"
import isOnline from "is-online"
import { getTimes } from "suncalc"
import { window } from "vscode"

import { getConfig } from "../editor.js"
import { LogLevel, getLogger } from "../logger.js"
import { addMinutes, isAfter } from "date-fns"
import { log } from "../logger.js"
import { Sundial, type Tides } from "../sundial.js"

interface Response {
lat: number
lon: number
}

let now = dayjs()
let end = now.add(-1, "minute")
let now = new Date()
let end = addMinutes(now, -1)

export async function getAutoLocale(): Promise<Tides> {
const log = getLogger("useAutoLocale")
now = new Date()

now = dayjs()

const timeout = now.isAfter(end, "minute")
const timeout = isAfter(now, end)
const context = Sundial.extensionContext

let latitude = context.globalState.get<number>("userLatitude")
let longitude = context.globalState.get<number>("userLongitude")

log.debug("Timeout:", timeout)
log.debug("Auto locale timeout", timeout)

const config = getConfig()
const connected = await isOnline()

if (connected && (timeout || config.sundial.debug === LogLevel.Debug)) {
end = now.add(5, "minute")
if (connected && timeout) {
end = addMinutes(now, 5)

try {
const { lat, lon }: Response = await got(
"http://ip-api.com/json/?fields=lat,lon",
).json()
const response = await fetch("http://ip-api.com/json/?fields=lat,lon")
const { lat, lon } = (await response.json()) as Response

latitude = lat
longitude = lon

context.globalState.update("userLatitude", latitude)
context.globalState.update("userLongitude", longitude)
} catch (error) {
log.error(error as string)
window.showErrorMessage(
"Oops, something went wrong collecting your geolocation! " +
"Maybe it is a problem with the API. Please create an issue " +
"on GitHub should this problem persist.",
)
if (error instanceof Error) {
log.error(error.message)
}
window.showErrorMessage("Fetching your location went wrong, please open an issue")
}
} else {
log.info("Not connected to internet, reusing existing geolocation")
log.info("Not connected, reusing existing geolocation")
}

if (!(latitude && longitude)) {
latitude = 0
longitude = 0
window.showInformationMessage(
"It seems you have been offline since the first start of VS Code, so we haven't had the chance to cache your location. Please go online or set your location manually.",
"Unable to fetch or use cached location, please set manually",
)
}

log.debug("Latitude:", latitude)
log.debug("Longitude:", longitude)
log.debug("Auto locale latitude", latitude)
log.debug("Auto locale longitude", longitude)

const tides = getTimes(now.toDate(), latitude, longitude)
const tides = getTimes(now, latitude, longitude)

return {
sunrise: dayjs(tides.sunrise),
sunset: dayjs(tides.sunset),
sunrise: tides.sunrise,
sunset: tides.sunset,
}
}
Loading

0 comments on commit 1bd6d23

Please sign in to comment.